How to clearInterval with unknown ID?

前端 未结 4 1784
眼角桃花
眼角桃花 2020-11-29 04:30

Say someone (evil) has set us a timer with setInterval, but we don\'t know its ID (we don\'t have the reference to the object, that setInterval is returning, no

4条回答
  •  一个人的身影
    2020-11-29 05:18

    From quick test, all major browsers (latest Chrome, Firefox and IE) give pretty small numbers as the ID so just looping "blindly" over all possible numbers should work just fine:

    function ClearAllIntervals() {
        for (var i = 1; i < 99999; i++)
            window.clearInterval(i);
    }
    

    Full example:

    window.onload = function() {
        window.setInterval(function() {
            document.getElementById("Tick").innerHTML += "tick
    "; }, 1000); window.setInterval(function() { document.getElementById("Tack").innerHTML += "tack
    "; }, 1000); }; function ClearAllIntervals() { for (var i = 1; i < 99999; i++) window.clearInterval(i); }
    #Placeholder div { width: 80px; float: left; }
    
    

    This will stop all intervals, can't stop specific interval without knowing its ID of course.

    As you can test for yourself, it should work on all major browsers mentioned above.

提交回复
热议问题