Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop $interval on leaving ui-state?

Angular, UI-router. Using $interval in a controller of a state like so:

$scope.Timer = null;

$scope.startTimer = function () { 
    $scope.Timer = $interval($scope.Foo, 30000);
};

$scope.stopTimer = function () {
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
};

The problem? The timer persists upon leaving the state. My understanding was that the $scope and the controller are essentially "destroyed" when a state is left. So, based on that, the timer should stop (Within the controller, I am cancelling the timer when moving around, that works - but it persists if I navigate to a diff state). What am I misunderstanding here?

I guess since interval and timeout are services in angular, they are available everywhere, but I still don't understand how they see functions in the not-initialized controller, unless it's copied. Is my solution to just use regular good-old js interval?

like image 525
VSO Avatar asked Jun 19 '15 13:06

VSO


1 Answers

clear interval on $destroy

Like this

$scope.$on("$destroy",function(){
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
});
like image 107
Anik Islam Abhi Avatar answered Sep 28 '22 09:09

Anik Islam Abhi