Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroying timeout on controller leave in AngularJS

Tags:

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?

like image 212
subZero Avatar asked Sep 30 '13 10:09

subZero


People also ask

How to stop timeout in AngularJS?

The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. To cancel a timeout request, call $timeout. cancel(promise) .

What is the difference between $timeout and setTimeout?

Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $. apply and parameters to be passed to the function.

What does $Timeout do in AngularJS?

The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.


1 Answers

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);
});
like image 160
subZero Avatar answered Sep 18 '22 18:09

subZero