如何在不知道其ID的情况下清除所有setInterval()和setTimeOut()?

如何在不知道其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 ); 

以此类推.