fraherm fraherm - 2 months ago 8
AngularJS Question

Stop $timeout when starting new controller

I'm polling for my data every 2 seconds to keep them updated on the page. My problem is when I visit another page the timeout stays active. How can i cancel my timeout when I visit an new page?

function IndexCtrl($scope, $timeout, RestData) {
$scope.rd = {};

(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$timeout(getRestDataFromServer, 2000);
});
})();
}


//EDIT
I found a solution, but I'm not sure if it's a good one. When i save my timeout to the $rootScope, I can cancel it in all the other controllers.

function IndexCtrl($scope, $rootScope, $timeout, RestData) {
$scope.rd = {};

(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$rootScope.prom = $timeout(getRestDataFromServer, 2000);
});
})();
}

function newPageCtrl($scope, $rootScope, $timeout) {
$timeout.cancel($rootScope.prom);
}

Answer

There are couple of Angular events that are being broadcasted when route is being changed. You can listen for them within the IndexCtrl using $scope.$on and act accordingly:

$destroy event

var promise = $timeout(getRestDataFromServer, 2000);
...

$scope.$on('$destroy', function(){
    $timeout.cancel(promise);
});

$locationChangeStart

var promise = $timeout(getRestDataFromServer, 2000);
...

$scope.$on('$locationChangeStart', function(){
    $timeout.cancel(promise);
});

$timeout() returns a promise object. This object can be supplied to $timeout.cancel() function to cancel the timeout.

Comments