一般来说定时器一旦设置,没有使用变量定义的话,定时器会变成匿名的定时函数存在与内存中。那么清除他们的时候如何找到他们呢?
var timer = setInterval( "func",1000 );
clearInterval( timer );
setInterval( "foo",1000 );
//如何清除????
MDN:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
The clearInterval() method of the WindowOrWorkerGlobalScope mixin cancels a timed, repeating action which was previously established by a call to setInterval().
SyntaxEdit
scope.clearInterval(intervalID)
Parameters
intervalID
The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval().
It's worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so.
每个定时器都会返回一个id,我们可以使用定时器的id来清除它;但是匿名定时器根本找不到id,因为没有使用变量保存,解决方法:
使用for,结束条件稍微设置大一些;
for( var i=0;i<100;i++ ){
clearInterval(i);
}
这样一次性清除了所有的定时器,当然也可以使用逻辑判断跳过不必要的清除动作。
**必要考虑:尽管已经清除了定时器,但是定时器的id任然存在于内存中,下次仍可以使用,如果不再调用的话,需要回收一下内存。对于非匿名定时器需要这样 timer = “” ; **