Reputation: 31
this is my controller:
.controller('mainController', function($http, $scope, $timeout, $sce, updateService) {
updateData = function() {
updateService.getDataA($http, $scope);
updateService.getDataB($http, $scope, $sce);
}
var updateIntervalId = setInterval(updateData, 1000);
})
Now when the user refreshes the page old requests are still being made, and I tried to cancel it by putting this under the interval call:
window.onbeforeunload = function() {
console.log('interval killed');
clearInterval(updateIntervalId);
}
the console is logging 'interval killed', so its being executed, but requests are still being made, why?
Upvotes: 1
Views: 939
Reputation: 28455
Let us do the angular way
Inject $interval
service in your controller
And update your code to following
var intervalPromise = $interval(updateData, 1000);
$scope.$on('$destroy', function() { // Gets triggered when the scope is destroyed.
$interval.cancel(intervalPromise );
});
And remove window.onbeforeunload
event handler.
Upvotes: 2
Reputation: 2454
When it comes to angularJS I would always recommend to use $interval
to handle intervals, since it works better with the angularJS hidden mechanics.
Then if the event window.onbeforeunload
lies outside the controller, you will never be able to access updateIntervalId
since it lies inside another scope, hence you should make it global.
Upvotes: 0