views:

903

answers:

2

Im building an automatic refreshing comment section for my website using jQuery .load. So I am using a javascript 'setTimeout' timer to check for new comments.

But after doing some stuff like changing comment pages or deleting (all using ajax), a few old timers keep running, even though I used clearTimeout before loading new ajax content.

Is there some way to clear ALL javascript timers when I load new ajax content?

+2  A: 

You may want to consider using jQuery Timers instead, which abstracts away many of the "ugly" details of setTimeout / setInterval, and makes them easier to use in your code for things like what you are describing.

Justin Ethier
+2  A: 

There's no general function in javascript that allows you to clear all timers. You will need to keep track of all timers you create. For this you could use a global array:

var timers = new Array();
...
// add a timer to the array
timers.push(setTimeout('someFunc()', 1000));
...
// clear all timers in the array
for (var i = 0; i < timers.length; i++)
{
    clearTimeout(timers[i]);
}
Darin Dimitrov
The problem is that my newer loaded ajax content has no control over the old running timers.
Jens
That's why I suggested a global variable.
Darin Dimitrov