subZero
subZero

Reputation: 5176

Destroying timeout on controller leave in AngularJS

I have a function like this, in an AngularJS controller

$timeout($scope.loadPosts, 5000); // pull every 5 seconds

When I navigate away from the controller (to another view), how can I stop the timeout and eventually destroy the controller so it is not running anymore?

Upvotes: 9

Views: 8777

Answers (1)

subZero
subZero

Reputation: 5176

I was able to solve it by listening for the $destroy event, like this:

var pull = $timeout($scope.loadPosts, 5000); // pull after 5 seconds

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

Upvotes: 18

Related Questions