How to remove all running $ interval in AngularJS?

Hi, I want to remove all running $interval in Angular. there are many $ intervals and button clicks on my page. I want to delete the entire interval. How do i do that.

Any help is appreciated.

+6
source share
2 answers

According to the documentation of $interval , a promise is returned, and the interval can be canceled with $interval.cancel(promise) .

I do not see any methods for canceling all intervals, but if you save the returned promises in an array, you can iterate over it to cancel all of them.

 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 distributed across different controllers, use the service to track them.

+10
source

More efficient 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()); } 
+4
source

Source: https://habr.com/ru/post/974142/


All Articles