如何在不知道其ID的情况下清除所有setInterval()和setTimeOut()? [英] How to clear all setInterval() and setTimeOut() without knowing their ID?

查看:1372
本文介绍了如何在不知道其ID的情况下清除所有setInterval()和setTimeOut()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不知道setInterval()setTimeOut()的返回值,是否仍可以使用clearInterveral(id)clearTimeOut(id)清除它们?

If I don't know the return value of setInterval() or setTimeOut(), can I still use clearInterveral(id) or clearTimeOut(id) to clear them?

谢谢.

推荐答案

您可以替换原始的setTimeout和setInterval,如:

You can replace original both setTimeout and setInterval like:

   setInterval = (function( oldsetInterval){
    var registered=[],
    f = function(a,b){
        return registered[ registered.length ] = oldsetInterval(a,b)
    };
     f.clearAll = function(){
        var r;
        while( r = registered.pop()) { 
           clearInterval( r );
        }       
    };
    return f;    
})(window.setInterval);

现在:

setInterval( function(){alert(5000)}, 5000 );
setInterval( function(){alert(10000)}, 10000 );

setInterval.clearAll();

建议@PointedEars发表评论,您不应使用相同的名字,

Suggesting a commentary from @PointedEars you shouldn't use the same name so:

reportingSetInterval = as above;
reportingSetInterval( function(){alert(5000)}, 5000 ); 

以此类推.

这篇关于如何在不知道其ID的情况下清除所有setInterval()和setTimeOut()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆