How to clearInterval with unknown ID?

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<br />";
    }, 1000);
    window.setInterval(function() {
        document.getElementById("Tack").innerHTML += "tack<br />";
    }, 1000);
};

function ClearAllIntervals() {
    for (var i = 1; i < 99999; i++)
        window.clearInterval(i);
}
#Placeholder div { width: 80px; float: left; }
<button type="button" onclick="ClearAllIntervals();">Clear All</button>
<div id="Placeholder">
    <div id="Tick"></div>
    <div id="Tack"></div>
</div>

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.

Leave a Comment