Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $interval function continues after route change

I have a function inside a controller which is based on setInterval. I noticed that after first calling it, it worked fine but continued even after the route changed. Afterwards i tried using the native $interval service which would automatically track changes in scope. The problem however remains. So now i have two questions. The first one is what can i do so that i use a repeated function inside a specific controller that stops when the user leaves that route? Also why does the scope function continue since i've changed scopes?

UPDATE - Code is like this

$scope.refreshScore() {         ....       } $scope.refreshMe = function(){   $interval($scope.refreshScore, 10000); } 
like image 417
anges244 Avatar asked Feb 05 '14 04:02

anges244


People also ask

How do I stop an interval in AngularJS?

To cancel an interval, call $interval. cancel(promise) . In tests you can use $interval. flush(millis) to move forward by millis milliseconds and trigger any functions scheduled to run in that time.

What is ng repeat end?

Overview. The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

What is attrs in AngularJS?

scope is an AngularJS scope object. element is the jqLite-wrapped element that this directive matches. attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. controller is the directive's required controller instance(s) or its own controller (if any).


1 Answers

Maybe try canceling it on the destroy event of the scope.

$scope.refreshScore() {    .... } var intervalPromise; $scope.refreshMe = function(){     intervalPromise = $interval($scope.refreshScore, 10000); } $scope.$on('$destroy',function(){     if(intervalPromise)         $interval.cancel(promiseFromInterval);    }); 

$interval may not be the best solution for this, especially if it is some async operation. If you absolutely have to have some timed operation that you want to occur preciously every x ms I would use something like this:

var refreshingPromise;  var isRefreshing = false; $scope.startRefreshing = function(){    if(isRefreshing) return;    isRefreshing = true;    (function refreshEvery(){          //Do refresh          //If async in then in callback do...          refreshingPromise = $timeout(refreshEvery,10000)     }()); }  

Then do the same thing as above

If you're having trouble canceling the refresh you might try subscribing to some sort of route change event. And doing it there.

like image 65
calebboyd Avatar answered Sep 17 '22 18:09

calebboyd