Clearing all javascript timeouts

The javascript setTimeout function allows you to execute a code snippet after a set interval. To stop the timeout you can use the clearTimeout method, this post looks at a couple of different methods of implementing this.

Clearing tracked timeouts vs clearing all timeouts

Tracking your different timeouts in an array is usually the best approach as this allows you to selectively stop the timeouts that only you created, meaning you won't accidently stop unrelated code. On the flip side of this however, there may be instances where stopping all timeouts is exactly what you want to do. We'll look at code to cover both these scenarios, best illustrated with an example...

Timeouts Example

We're going to setup three timeouts, two of which are tracked in a 'timeouts' array, and one 'rogue' timeout that isn't being tracked. We'll start by setting up two buttons to stop either just the tracked timeouts, or clear all timeouts.

<input type="button" id="stopTracked" value="Stop Tracked Alerts!" />

<input type="button" id="stopEverything" value="Stop All Alerts!" />


Next we'll setup all the javascript to track timeouts and start a rogue timeout, as well as adding click events to the buttons:

var timeouts = [];

// Tracked timeouts
timeouts.push(setTimeout(function(){alert('hello');}, 2000));
timeouts.push(setTimeout(function(){alert('world');}, 4000));

// Rogue timeout
setTimeout(function(){alert('rogue timeout!')},6000);

$('#stopTracked').click(function() {
    alert('Tracked timeouts cleared!');

$('#stopEverything').click(function() {
    alert('All timeouts cleared!');

Lastly we add functions for the two different options:

Clear tracked timeouts

This function works by looping through each of the items in the timeouts array and clearing them.

function stopTracked()

    for(var i=0; i<timeouts.length; i++)

    timeouts = [];

Clearing all timeouts

The second option is to clear every timeout running which will also catch the 'rogue'. This works by adding a new null timeout that will return an id that represents the total number of timeouts available. Using the total we then simply countdown using a while loop clearing each timeout as we go. This code will guarentee to clear everything without any tracking, however is less efficient as it requires an additional empty timeout to be created.

function stopAllTimeouts()
    var id = window.setTimeout(null,0);
    while (id--)

Sign Up
comments powered by Disqus

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.