How to stop $interval on leaving ui-state?

7.2k views Asked by At

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?

1

There are 1 answers

5
Anik Islam Abhi On BEST ANSWER

clear interval on $destroy

Like this

$scope.$on("$destroy",function(){
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
});