Mukund Kumar
Mukund Kumar

Reputation: 23191

$interval function continues when I change routes

I am getting a problem regarding an $interval function continues when I change routes.

This is the code:

  x = 2;

 var multiply = function () {
     x = x * 2;
     if (x == 134217728) {
         $interval.cancel($scope.stop);
         $scope.stop = 0;
     }
 }


 $scope.Result = function () {
     $scope.stop = $interval(multiply, 1000);
 }

 $scope.Result();

When x<134217728, I change the route to move to another page. The problem is that $interval doesn't stop after the route changes. I store the promise in the variable stop in the $scope model. I think $scope doesn't destroy after routes change and that is why $interval continues.

How can I solve this issue ?

Upvotes: 6

Views: 4392

Answers (2)

ryeballar
ryeballar

Reputation: 30088

you can use $interval.cancel($scope.stop); when $locationChangeSuccess is invoked in your controller/service.

E.G.

controller('MyController', function($rootScope, $interval) {
  $scope.stop = $interval(yourOperation, 1000);

  var dereg = $rootScope.$on('$locationChangeSuccess', function() {
    $interval.cancel($scope.stop);
    dereg();
  });

  function yourOperation() {}
};

Upvotes: 14

Manish P
Manish P

Reputation: 3

Because you are injecting $interval in other controller too, you can either set the $interval in other controller or you can cancel the $interval with $locationChangesuccess as mentioned by @ryeballar.

Upvotes: 0

Related Questions