Angular documentation about $interval
is saying :
Note: Intervals created by this service must be explicitly destroyed when you are finished with them.
but it's not explaining how to destroy the $interval.
If for example I have a directive containing this code :
$interval(function() { for (var i in myArray) { // do domething } }, 5000);
How can i destroy it when the user changes the page for example?
$rootScope is a parent object of all “$scope” angular objects created in a webpage. $scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive.
Scope Hierarchies Every angularJS application can have only one root scope as it is the parent scope. But it can have more than one child scope. New scopes can be created by directives which are added to parent scope as child scope.
Whenever the user changes the page, the scope associated with the controller of the route (/page1
in the example below) will be sent a $destroy
event. You can cancel
that $interval
in a listener to that event:
app.config(function ($routeProvider) { $routeProvider.when('/page1', { template: '<div>Page Content</div>', controller: PageController }); // ... }); function PageController($scope, $interval) { var intervalPromise = $interval(function () { /* ... */ }, 5000); $scope.$on('$destroy', function () { $interval.cancel(intervalPromise); }); }
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