How to clear all setInterval() and setTimeOut() without knowing their ID?

橙三吉。 提交于 2019-12-19 11:36:09

问题


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

Thanks.


回答1:


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);

And now:

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

setInterval.clearAll();

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

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

and so on..




回答2:


You can use a register pattern based object for this.




回答3:


As far as I know, this is not possible without the original id, so storing that, maybe in an array would be a good idea



来源:https://stackoverflow.com/questions/8769598/how-to-clear-all-setinterval-and-settimeout-without-knowing-their-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!