Reputation: 14393
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?
Upvotes: 35
Views: 35706
Reputation: 34288
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); });
}
Upvotes: 79