[ACCEPTED]-Is there a way to clear all JavaScript timers at once?-timer

Accepted answer
Score: 43

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

If you must:

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

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

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

There's no general function in javascript 4 that allows you to clear all timers. You 3 will need to keep track of all timers you 2 create. For this you could use a global 1 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++)
Score: 2

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

Score: 1

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

More Related questions