Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$interval function continues when I change routes

Tags:

angularjs

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 ?

like image 660
Mukund Kumar Avatar asked Jun 20 '14 10:06

Mukund Kumar


People also ask

How to set interval in JavaScript?

The JavaScript setInterval () method returns an ID which can be used by the clearInterval () method to stop the interval. If you only need to execute a function one time, use the setTimeout () method. JavaScript interval to be set use setInterval () function.

How does The setInterval function work in take a ride?

On clicking the “Take a Ride” button, the SetInterval function is activated, which in return displays an alert in the form of a pop-up that has the message as shown in the output below. And this alert goes on forever. <p>Visit our Website to Explore new and latest courses and Training Programs.

What is the difference between setInterval () and 1 second interval?

For example, if the code originally used setInterval () to run some code every 50 ms, once the application is moved to a background tab, the interval automatically becomes 1000 ms (1 second). However once the tab is re-activated, the original interval or delay returns to the original value.

How to execute setInterval function without delay for the first time in JavaScript?

How to execute setInterval function without delay for the first time in JavaScript ? The setInterval () method always invokes the function after the delay for the first time using two approaches: Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function.


1 Answers

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() {}
};
like image 189
ryeballar Avatar answered Oct 21 '22 14:10

ryeballar