How to remove all running $interval in AngularJS?

Rituraj ratan picture Rituraj ratan · Aug 21, 2014 · Viewed 8.1k times · Source

Hi i want to remove all running $interval in Angular. in my page there are many $interval and on button click i want to remove all interval.How will i do it .

Any help is appreciated.

Answer

ivarni picture ivarni · Aug 21, 2014

According to the documentation $interval returns a promise, and the interval can be cancelled using $interval.cancel(promise).

I can't see any methods for cancelling all intervals, but if you keep the returned promises in an array you can iterate over that to cancel them all.

var intervals = []
intervals.push($interval(function() { /*doStuff*/ }, /*timeout*/));
intervals.push($interval(function() { /*doDifferentStuff*/ }, /*timeout*/));

...

angular.forEach(intervals, function(interval) {
    $interval.cancel(interval);
});
intervals.length = 0; //clear the array

If your intervals are spread over different controllers, use a service to keep track of them.