Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 381
Jens Avatar asked Dec 13 '09 15:12

Jens


People also ask

Does clearTimeout clear all timeouts?

To clear all timeouts they must be "captured" first: Place the below code before any other script and it will create a wrapper function for the original setTimeout & clearTimeout . 💡 New clearTimeouts methods will be added to the window Object, which will allow clearing all (pending) timeouts (Gist link).

How do I clear set timeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

How do you end a timer in JavaScript?

Clicking the Stop button clears the timer by using the clearInterval(), passing in the 'check' variable that is returned by the call to setInterval().

Does JavaScript have a timer function?

There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.


1 Answers

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) {      clearTimeout(i); } 
like image 180
Omar Al-Ithawi Avatar answered Sep 27 '22 18:09

Omar Al-Ithawi