Clear all setIntervals

孤人 提交于 2019-12-05 11:20:52

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.

There's no "clear-all-intervals" function.

You'll need to store all of them, and clear all of them:

var ints = [];

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

             }, 1000) 
  );
});

// later

for ( var i = 0; i < ints.length; ++i )
  clearInterval( ints[i] );

ints = [];   // and forget them
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( );

If you are wanting to be compatible with IE8 or under you should shim .forEach, or replace it with a library equivalent, or a plain loop.

Since each interval is associated with an element, you could store the interval ID in the element:

$(".elements").each(function() {
  $(this).data('interval-id', setInterval(function() {
    // ...
  }, 1000));
});

Then, if you want to clear the intervals,

$(".elements").each(function() {
  clearInterval($(this).data('interval-id'));
});

I don't recommend you use this solution, but it really do the trick. The idea it to override setInterval function to collect all links to setInterval:

(function(originalSetInterval){
    var intervals = [];
    window.setInterval = function(func, timeout) {
        var newInterval = originalSetInterval(func, timeout);
        intervals.push(newInterval);
        return newInterval;
    }

    window.clearAllIntervals = function() {
        intervals.forEach(clearInterval);
    }
})(window.setInterval)

To do a better job you would also need to override clearInterval to remove all intervals being clear already:

(function(originalSetInterval, originalClearInterval){
    var intervals = [];
    window.setInterval = function(func, timeout) {
        var newInterval = originalSetInterval(func, timeout);
        intervals.push(newInterval);
        return newInterval;
    }

    window.clearInterval = function(interval) {
        originalClearInterval(interval);
        intervals.splice(intervals.indexOf(interval), 1)
    }

    window.clearAllIntervals = function() {
        intervals.forEach(clearInterval);
    }
})(window.setInterval, window.clearInterval)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!