Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs stop $interval for specific controller

I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function.

like image 849
jana91 Avatar asked Mar 13 '23 09:03

jana91


2 Answers

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

You could use the cancel method to clean $interval object. You should cancel out the interval while leaving the controller.

For that you need to add eventListener over $scope's $destroy event, you could do cleaning stuff (eg. canceling interval object, canceling timeout object).

Code

var myInterval = $interval(function(){
   //your interval code
}, 1000)

//register this listener inside your controller where the interval belongs.
$scope.$on('$destroy', function(){
    $interval.cancel(myInterval)
});

Sample Plunkr

like image 86
Pankaj Parkar Avatar answered Mar 19 '23 07:03

Pankaj Parkar


Add the interval variable in rootScope. And cancel it in the second controller whenever it gets opened as shown below.

First Controller

$rootScope.stopInterval = $interval(function(){
   //code goes here
}, 1000);

Second Controller

$interval.cancel($rootScope.stopInterval);

Note: Only flaw in this case is you need to stop it in all the controllers you use after first controller, but a reliable one.

like image 26
vamshi krishna kurella Avatar answered Mar 19 '23 09:03

vamshi krishna kurella