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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With