9

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.

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55

2 Answers2

13

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.

ivarni
  • 17,658
  • 17
  • 76
  • 92
  • i agree with your answer thanks for giving your time . i am thinking that is some property in angular by which we can remove all $interval but thanks now i will make a service regarding your logic :) – Rituraj ratan Aug 21 '14 at 07:23
5

A more performant approach :

var intervals = [];

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

//doing some stuff

while(intervals.length){
    $interval.cancel(intervals.pop());
}
Freezystem
  • 4,494
  • 1
  • 32
  • 35
  • 2
    First there are less operations on a table that decrease its size along iterations. At the end you're sure all intervals in the array have been stopped. Even the ones coming during the process. Finally i'm not declaring any anonymous function so less memory is used. But you're right the performance gap is clearly negligible between this 2 codes. Just wanted to share my shorter solution. =) – Freezystem Jan 15 '16 at 12:44