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 ?
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.
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.
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 ? 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.
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() {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With