61

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) {  }
Nikolay Dyankov
  • 5,456
  • 10
  • 48
  • 72

4 Answers4

72

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.

Mike 'Pomax' Kamermans
  • 44,582
  • 14
  • 95
  • 135
Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158
  • This snippet DID work, but it causes some weird side effects. Here's the plugin: http://www.nikolaydyankov.com/Dev/mosaic - try playing with the settings below and see how the transitions simply stop working. I tried to debug this, logged all of the variables, tested all new intervals and nothing. It just won't work. – Nikolay Dyankov Dec 26 '11 at 12:30
  • 16
    This is not a good idea. [The specification](http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#list-of-active-timeouts) does not guarantee any specific order for the handles, only that they are numeric and unique. – John Dvorak May 26 '13 at 15:42
  • 1
    The spec states "Let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call." That is, positive and unique. No other guarantees. – John Dvorak May 26 '13 at 15:47
  • 1
    Bad idea, for the reason @JanDvorak specified and because it will also stop intervals that were not created by your code. – ThiefMaster May 26 '13 at 15:53
  • Additionally, `window.setInterval('', 9999);` returns "undefined" for me. Even with an empty function passed instead, the above still applies – John Dvorak May 26 '13 at 15:53
  • while in theory the specification does not guarantee a specific order, as a *practical* answer, based on what browsers do in reality, this answer is just fine. Firefox, Webkit browsers and IE all generate sequential interval numbers (presumably because that's the easiest way to meet the spec. It would be *insane* to come up with a better unique sequence than an incremented uuid) – Mike 'Pomax' Kamermans Jul 12 '14 at 23:24
  • Initially this worked for me, but as my app got more complicated it caused all sorts of problems. For example, jQuery's fadeOut function uses intervals, so due to a race condition the fadeOut callback function was never called, so be mindful when using this shotgun approach! – Ben Southall May 15 '15 at 08:44
  • 1
    This is a welcoming message for all sorts of hard-to-catch bugs ... It's better if you keep track of what intervals you created in an array or an object, and only clear those ... – benjaminz Feb 16 '17 at 21:07
  • **NOTE** [Depending on the implementation, `clearInterval` may also clear _timeouts_, and `clearTimeout` may also clear _intervals_.](https://stackoverflow.com/questions/9913719/are-cleartimeout-and-clearinterval-the-same) – Константин Ван May 19 '19 at 16:59
  • Not just depending on the implementation: the HTML standard clearly states that [they do the exact same thing](https://html.spec.whatwg.org/#timers). It doesn't matter whether a timer is associated with a timeout or an interval. Also, as upvoted as this answer is: _it's incorrect_. The HTML standard clearly states that the actual numbers you get from setTimeout/setInterval are `implementation specific` meaning there is literally no requirements on the logic for numbering, and the idea behind this answer is something you _explicitly_ can't rely on. It just "happens to work, in this browser". – Mike 'Pomax' Kamermans Jul 26 '21 at 16:24
71

Store 'em in an object. Since you're the only one making these intervals, and you know what they are, you can store them and later mess with them as you wish. I'd create an object dedicated for just that, something like:

var interval = {
    // to keep a reference to all the intervals
    intervals : new Set(),
    
    // create another interval
    make(...args) {
        var newInterval = setInterval(...args);
        this.intervals.add(newInterval);
        return newInterval;
    },

    // clear a single interval
    clear(id) {
        this.intervals.delete(id);
        return clearInterval(id);
    },

    // clear all intervals
    clearAll() {
        for (var id of this.intervals) {
            this.clear(id);
        }
    }
};

Your first question might be

Why make a separate object for just that?

Well Watson, it's to keep your hand-made intervals related to your plugin/project away from prying eyes, so you won't mess with other intervals being set in the page not related to your plugin.

Yes, but why can't I store it inside the base object?

You most certainly can, but I think this way is much cleaner. It separates the logic you do in your base with the weird timeout logic.

Why did you store the intervals inside a Set and not an array?

Faster access and a little bit of cleaner code. You can go either way, really.

SuperStormer
  • 4,531
  • 5
  • 20
  • 32
Zirak
  • 37,288
  • 12
  • 78
  • 90
  • I used an array as a data structure, but anyhow, this is the correct approach. One can even have different interval "wrappers" in case you don't want to kill all. Good answer! – benjaminz Feb 16 '17 at 21:06
19

Intialize Timer and set it as window object. Window.myInterval will hold the ID of the Timer.

like window.myInterval = setInterval(function() { console.log('hi'); }, 1000);

To clear Interval you can write like

if(window.myInterval != undefined && window.myInterval != 'undefined'){
    window.clearInterval(window.myInterval);
    alert('Timer cleared with id'+window.myInterval);
}
YakovL
  • 6,451
  • 11
  • 52
  • 82
Shujaath Khan
  • 1,182
  • 14
  • 22
1

When you set an interval, you get a pointer to it. To clear all intervals, you'll need to store all of them:

// Initially
var arr = [];
arr.push(setInterval(function () {
    console.log(1);
  }, 1000));
arr.push(setInterval(function () {
    console.log(2);
  }, 1000));
arr.push(setInterval(function () {
    console.log(3);
  }, 1000));
  

Following loop will clear all intervals

// Clear multiple Intervals
  arr.map((a) => {
    console.log(a)
    clearInterval(a);
    arr = [];
  })
ashish siddhu
  • 181
  • 1
  • 5