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

前端 未结 3 674
北恋
北恋 2021-01-16 15:10

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

相关标签:
3条回答
  • 2021-01-16 15:43

    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..

    0 讨论(0)
  • 2021-01-16 15:59

    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

    0 讨论(0)
  • 2021-01-16 16:00

    You can use a register pattern based object for this.

    0 讨论(0)
提交回复
热议问题