javascript: Clear all timeouts?

Is there a way to clear all time outs from a given window? I suppose the timeouts are stored somewhere in the window object but couldn't confirm that.

Any cross browser solution is welcome.


They are not in the window object, but they have ids, which (afaik) are consecutive integers.

So you may clear all timeouts like so:

var id = window.setTimeout(function() {}, 0);

while (id--) {
    window.clearTimeout(id); // will do nothing if no timeout with id is present
}

I think the easiest way to accomplish this would be to store all the setTimeout identifiers in one array, where you can easily iterate to clearTimeout() on all of them.

var timeouts = [];
timeouts.push(setTimeout(function(){alert(1);}, 200));
timeouts.push(setTimeout(function(){alert(2);}, 300));
timeouts.push(setTimeout(function(){alert(3);}, 400));

for (var i=0; i<timeouts.length; i++) {
  clearTimeout(timeouts[i]);
}

I have an addition to Pumbaa80's answer that might be useful for someone developing for old IEs.

Yes, all major browsers implement timeout ids as consecutive integers (which is not required by specification). Althrough the starting number differs form browser to browser. It seems that Opera, Safari, Chrome and IE > 8 starts timeout ids from 1, Gecko-based browsers from 2 and IE <= 8 from some random number that is magically saved across tab refresh. You can discover it yourself.

All that meens that in IE <=8 the while (lastTimeoutId--) cycle may run over 8digits times and show the "A script on this page is causing Internet Explorer to run slowly" message. So if you can not save all you timeout id's or don't want to override window.setTimeout you may consider saving the first timeout id on a page and clearing timeouts until it.

Execute the code on early page load:

var clearAllTimeouts = (function () {
    var noop = function () {},
        firstId = window.setTimeout(noop, 0);
    return function () {
        var lastId = window.setTimeout(noop, 0);
        console.log('Removing', lastId - firstId, 'timeout handlers');
        while (firstId != lastId)
            window.clearTimeout(++firstId);
    };
});

And then clear all pending timeouts that probably was set by foreign code so many times you want