MonsterMMORPG MonsterMMORPG - 11 months ago 56
Javascript Question

How can I disable all setTimeout events?

I am using ajax and iI have a javascript function which creates many other javascript functions with setTimeout. After asynchronous postback happenes, I want to disable all of these setTimeouted events. How can I do that?


When you call setTimeout(), store the timer ID so you can clear it. If you're creating many timeouts, then an array is a good option for storing the IDs. For example:

var timeouts = [];
//then, store when you create them
timeouts.push( setTimeout( { ... }, 1000) );

Then when you want to clear them:

for (var i = 0; i < timeouts.length; i++) {
//quick reset of the timer array you just cleared
timeouts = [];

As @Robert noted below, clearTimeout() won't throw an error if the timeout has already occurred, so there are no race/timing issues here.