Angular: Why Should You Care About $destroy when $timeout

29 בOctober 2014

tags: ,
no comments

$timeout is a service that is used to invoke a function after a given amount of time.

Untitled

For example, invoking an alert(“hello world”) call after 1000 milliseconds would look as following:

Untitled2

$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.

Untitled2

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:

Untitled2

The $timeout returns a promise which is cancelled when the page $destroy event is called.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*