$timeout is a service that is used to invoke a function after a given amount of time.
For example, invoking an alert(“hello world”) call after 1000 milliseconds would look as following:
$timeout – when will it stop?
But, have you ever consider what happens with the timeout call when you leave the page your in? Let’s say the user clicks on a link and moves into a different ng-view that has a new controller. Will the $timeout call still be fire, calling your function unexpectedly even after the user has left the page?
It seems the $timeout call will still be invoked, even after the page is no longer viewed, the controlle’s $destroy method has been called. Even the AngularJS Batarang which usually does a great job in clearing out which scopes are involved, won’t help finding who’s calling since the calling scope is no longer a part of the current DOM tree.
Preventing unexcpected $timeout calls is pretty simple and involves a habit of always cancelling a timeout. You just have to consider the case where the timeout is not relevant anymore, and that is usually the time when $scope.$destroy() is called. See the following code snippet for a reference to prevent additional timeout calls when the user leaves the page:
The $timeout returns a promise which is cancelled when the page $destroy event is called.