Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clearInterval() for all setInterval()?

People also ask

Can you clearInterval within setInterval?

Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.

How do I stop all setInterval?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.


This can be one of logic to clear all interval...

for (var i = 1; i < 99999; i++)
        window.clearInterval(i);

You can override setInterval:

window.oldSetInterval = window.setInterval;
window.setInterval = function(func, interval) {
    var interval = oldSetInterval(func, interval);
    // store it in a array for stopping? stop it now? the power is yours.
}

No, you can't, not without the original variable.


The answer

for (var i = 1; i < 99999; i++)
     window.clearInterval(i);

was the one I was looking for. With a little improvement of this very simple logic, I was able to do something like this.

var i = 0;
var rotatorId;
var rotator;

rotator =  setInterval(function() {myfunction(), 3000});
rotatorId[i] = rotator;
i++;

if (rotator > 1) {
   for(i = 1; i < rotatorId.length; i++){
      clearInterval(rotatorId[i]);                      
    }                       
}

The way I have achieved this is by having an application level array (e.g., Application.setIntervalIds = []) to which I push the setInterval ids to whenever one is created. Then I can simply call window.clearInterval(id) on each id in the array when I need to.

As an example, when I create a new setInterval I write something like (coffeescript):

id = setInterval (() -> function2call()), timeout
Application.setIntervalIds.push id

And then I have a clearAllSetIntervals function I can call when needed:

Application.clearAllSetIntervals = () ->
    $.each Application.setIntervalIds, (index, id) ->
         window.clearInterval id

Best way i found ...

var clearAllIntervals = function ( ) {

    var intervals = [];

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

        }, 1000) );
    });

    return function clearAll ( ) {
        intervals.forEach( clearInterval );
    }

}( );

// When you want to clear them:
clearAllIntervals( );