js setTimeout()

来源:互联网 发布:java中reverse函数 编辑:程序博客网 时间:2024/05/29 16:07

使用setTimeout时需注意,当该代码执行时,JS会立即编译函数第一个参数”code”,所以该函数的第一个参数应该为:需要编译的代码、或者一个函数。

var t=setTimeout(alert('15 seconds!'),15000);//15 seconds!会立马跳出来,延时没有效果var t=setTimeout("alert('15 seconds!')",15000);var t=setTimeout(function(){alert('15 seconds!')},15000);

function setReload(){window.location.reload();var t=setTimeout('setReload()',30000);//没有延时效果}

应修改为

var t=setTimeout(function(){window.location.reload();},30000)

倒计时计时器: timename=setTimeout(“function();”, delaytime);
循环定时器: timename=setInterval(“function();”, delaytime);
倒计时定时器是在指定时间到达后触发事件,而循环定时器就是在间隔时间到来时反复触发事件,两者的区别在于:前者只是作用一次,而后者则不停地作用。
setInterval为自动重复,setTimeout不会重复。
clearTimeout(对象)清除已设置的setTimeout对象。
clearInterval(对象)清除已设置的setInterval对象。

var loop=0;var t;$().ready(function(){$('.btn-refresh').click(function(){t=setInterval(show,1000);// clearInterval(t);//这里会顺序执行,导致定时器没有发生作用});});function show(){loop++;alert(loop);alert("hello world!");if(loop==3){clearInterval(t);}}




















0 0
原创粉丝点击