Window setTimeout() 方法 Window setInterval() 方法 带参数使用

139 阅读1分钟

不带参数使用请看:
www.runoob.com/jsref/met-w…
带参数使用
setInterval(funcName, 3000,参数1,参数2);

注意 functionName只为名字 不要带()

备注:

setInterval("fun()",time)有两个参数;
fun()为要执行的函数;
time为多久执行一次函数,单位是毫秒;

我们做一个简单的例子,就是每隔5s弹出一个“hello”的对话框。


先看第一种写法,把方法体抽离出来,以字符串的形式调用函数名,这种写法调用函数名是不能传参的:

<script type="text/javascript">
  setInterval("hello()",5000);
  function hello(){
    alert("hello");
  }
</script>

第二种写法是把要执行的代码以字符串形式放在setInterval()的参数里,它可以传参数;个人不喜欢这种写法,拼接起来容易混淆。

<script type="text/javascript">
    var word = "hello";
    setInterval("alert('"+word+"')",5000);
</script>

第三种写法是把方法抽离出来,但不以字符串的形式调用函数名,使用它传递参数相对比较清晰;

复制代码

<script type="text/javascript">
    setInterval(function(){
        hello("hello");
    },5000);

    function hello(word){
        alert(word);
    }
</script>        

复制代码

window.onload=function(){\
var aLi=document.getElementsByTagName('li');\
for(var i=0; i<aLi.length; i++){\
aLi[i].onmouseover=function(){\
var oSubNav=this.getElementsByTagName('ul')[0];\
if(oSubNav){\
var This=oSubNav;\
clearInterval(This.time);\
This.time=**setInterval**(function(){\
This.style.height=This.offsetHeight+16+"px";\
if(This.offsetHeight>=120)\
clearInterval(This.time);\
},30)\
}\
}\
//鼠标离开菜单,二级菜单动画收缩起来。\
aLi[i].onmouseout=function(){\
var oSubNav=this.getElementsByTagName('ul')[0];\
if(oSubNav){\
var This=oSubNav;\
clearInterval(This.time);\
This.time=**setInterval**(function(){\
This.style.height=This.offsetHeight-16+"px";\
if(This.offsetHeight<=0)\
clearInterval(This.time);\
},30)\
}\
}\
}\
}


window.onload=function(){\
var aLi=document.getElementsByTagName('li');\
for(var i=0; i<aLi.length; i++){\
aLi[i].onmouseover=function(){\
var oSubNav=this.getElementsByTagName('ul')[0];\
if(oSubNav){\
var This=oSubNav;\
clearInterval(This.time);\
This.time=**setInterval**(function(){\
This.style.height=This.offsetHeight+16+"px";\
if(This.offsetHeight>=120)\
clearInterval(This.time);\
},30)\
}\
}\
//鼠标离开菜单,二级菜单动画收缩起来。\
aLi[i].onmouseout=function(){\
var oSubNav=this.getElementsByTagName('ul')[0];\
if(oSubNav){\
var This=oSubNav;\
clearInterval(This.time);\
This.time=**setInterval**(function(){\
This.style.height=This.offsetHeight-16+"px";\
if(This.offsetHeight<=0)\
clearInterval(This.time);\
},30)\
}\
}\
}\
}