Search code examples
javascriptjqueryset

How do I clear all intervals?


I am using

varName = setInterval(function() { ... }, 1000);

to set a couple of intervals in a jquery plugin that I'm writing, but when the plugin is reloaded I need to clear those intervals. I tried storing them in variables, like this:

(function($){
$.mosaicSlider = function(el) {
    var base = this;        
    var transitionInterval, mainInterval;

...

base.init = function() {
    mainInterval = setInverval(function() { ... }, 1000);
}

base.grid = function() {
    this.transition() = function() {
         transitionInterval = setInterval(function(...) {
    }
}

base.init();

And I tried killing those intervals in the base.init() function, like this:

clearInterval(transitionInterval);
clearInterval(mainInterval);

And like this:

window.oldSetInterval = window.setInterval;
window.setInterval = new function(func, interval) {  }

Solution

  • You can find the "highest" timer identifier by creating a new timer that does "nothing" (by giving it an empty function to run, scheduled to run decades in the future), and then clear every timer between ids 1 and that identifier, like so:

    // Get a reference to the last interval + 1
    const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
    
    // Clear any timeout/interval up to that id
    for (let i = 1; i < interval_id; i++) {
      window.clearInterval(i);
    }
    

    However, note that this is not guaranteed to work: the HTML standard does not actually prescribe how timeout/interval identifiers get allocated, so the assumption that we'll get a reference to the "last interval identifier + 1" is merely that: an assumption. It might be true for most browsers at the time of this answer, but there is no guarantee that's that will still be the case even in the next version of the same browser.