清除匿名定时器

一般来说定时器一旦设置,没有使用变量定义的话,定时器会变成匿名的定时函数存在与内存中。那么清除他们的时候如何找到他们呢?

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 = “” ; **

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值