How to remove all running $interval in AngularJS?
Asked Answered
N

2

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.

Nardone answered 21/8, 2014 at 7:12 Comment(0)
S
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.

Sianna answered 21/8, 2014 at 7:19 Comment(1)
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 :)Nardone
B
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());
}
Busch answered 15/6, 2015 at 13:33 Comment(1)
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. =)Busch

© 2022 - 2024 — McMap. All rights reserved.