Cancel a AngularJS $timeout on routeChange

On a specific page in my application I think of doing a server-call to update information on a set interval. I stumbled upon a problem though. I want to cancel my $timeout when a user navigates away from the page in question so that the application doesn't try to work with stuff that isn't there anymore.

Any ideas on how to work around this?

Use $timeout.cancel like this:

yourTimer = $timeout(function() { /* ... */ }, 5000);
$timeout.cancel(yourTimer);

Reference

You can also cancel your timer inside of your anonymous function instead of outside of it.

var timer = $timeout(function(){
  // do something here...
  $timeout.cancel(timer); // I automatically cancel myself after running.
}, 1000);