javascriptjquerysetintervalclearinterval

Clear all setIntervals


I'm using setIntervals within an each() function like so

$(".elements").each(function() {
    setInterval(function() {

    }, 1000);
});

Obviously a setIntervals is created for each element.

My question is: How do I clear all the setIntervals when I no longer need them? I have tried storing the setInterval in a variable and call window.clearInterval(int), but that only clears the last setInterval since each variable is overridden.


Solution

  • When you set an interval, you get a pointer to it:

    var myInterval = setInterval(function(){}, 4000);
    

    If you want to cancel an interval, you do the following:

    clearInterval(myInterval); 
    

    So, for what you want to do, you would do the following:

    var intervals = [];
    $(".elements").each(function() {
        var i = setInterval(function() {
    
        }, 1000);
        intervals.push(i);
    });
    

    Then if you need to cancel them all you can do this:

    intervals.forEach(clearInterval);
    

    That should do it for you.