请注意,setTimeout
和setInterval
是非常不同的功能:
setTimeout
将在超时后执行一次代码。
setInterval
将在提供的超时间隔内永远执行代码。
这两个函数都返回一个计时器 ID,您可以使用它来中止超时。您所要做的就是将该值存储在一个变量中,并将其分别用作clearTimeout(tid)
或 的参数clearInterval(tid)
。
因此,根据您想要做什么,您有两个有效的选择:
// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
// do some stuff...
tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}
或者
// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
两者都是实现相同目标的非常常见的方法。