Is there a way to clear all JavaScript timers at once?

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?



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 = [];
// 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++)

Warning: My code bellow is problematic, mainly because the requirement is itself is problematic. I wonder why would you want to clear all timers any way. This makes your code breaking any plugin the uses the timers. Which is much more common than you may think, unless of course you're debugging or having fun, then it doesn't matter.

If you must:

This is one of the worst possible solutions. However it reveals a potential security vulnerability in JavaScript itself. But since it just works (clears ALL of the timers) I thought it would be cool to share it:

var maxId = setTimeout(function(){}, 0);

for(var i=0; i < maxId; i+=1) { 

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.


This might help. I have a case that user is the one who is creating the timers, something like an open platform for development, obviously I don't have access to ID of those timers. So I need to sandbox them and remove them all if necessary. To do that I create a hidden <iframe> and load all timers in that iframe. To remove all timers, simply remove the iframe.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.