如果您希望在页面刷新时执行超时功能,您只需将功能添加到window.onload
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
window.onload = timeout;
这对我来说很好
如果你希望它被执行多次,然后去setInterval()
var timeout = setInterval(function(){
alert('this is executed for each second');
}, 1000);
window.onload = timeout;
它会一直执行到你调用clearInterval(timeout);
如果你想要多个超时,那么你应该做这样的事情
var timeout = setTimeout(function(){
alert('this is executed after 1 second');
}, 1000);
var timeout1 = setTimeout(function(){
alert('this is executed after 2 seconds');
}, 2000);
var timeout2 = setTimeout(function(){
alert('this is executed after 3 seconds');
}, 3000);
window.onload = timeout;timeout1;timeout2;
这是因为 setTimeout 会在页面刷新后立即计算时间,这对我来说很好用