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?
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).
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.
Clicking the Stop button clears the timer by using the clearInterval(), passing in the 'check' variable that is returned by the call to setInterval().
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With