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?
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) .
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With