Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs $interval being called multiple times

Tags:

angularjs

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??

like image 217
harishr Avatar asked Dec 02 '25 08:12

harishr


1 Answers

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);
});
like image 77
JB Nizet Avatar answered Dec 05 '25 03:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!