angularjs $interval being called multiple times

Problem

inside controller i am calling $interval to make a function call after every second kind of stopwatch service.

but the problem is the function gets called as many times as i come back to this router, e.g. if i go to another menu and come back here.. the timer would be changed twice.. if i do it again then trice.

i have tried below 3 methods in route all with same result in the controller:

$timeout(updateTimer, 1000);

setInterval(function () { $scope.$apply(updateTimer); }, 1000);

$interval(updateTimer, 1000);

why is the timer called as many times as i come back to this page??

Problem courtesy of: harishr

Solution

Ech time a route is called, the controller assciated to this route is instantiated. And you're starting an interval each time your controller is instantiated. So you get this result.

Make sure to cancel your interval when the controller is not used anymore. The official documentation has a specific warning about this situation, and an example showing how to cancel the interval once the controller isn't used anymore:

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

var stop = $interval(...);

$scope.$on('$destroy', function() {
    // Make sure that the interval is destroyed too
    $interval.cancel(stop);
});
Solution courtesy of: JB Nizet

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.