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...
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!" />
var timeouts = ;
// Tracked timeouts
// Rogue timeout
alert('Tracked timeouts cleared!');
alert('All timeouts cleared!');
Lastly we add functions for the two different options:
This function works by looping through each of the items in the timeouts array and clearing them.
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.
var id = window.setTimeout(null,0);