Winnemucca
Winnemucca

Reputation: 3458

Cancelling $interval with promise after condition is met with Angular timer

I am having a difficult time getting my $interval service to cancel. I am not entirely sure what it is that I am missing.

I have initialed a counter that is counting down a counting property. $scope.sessionCounter

           $scope.sessionCounter = 5;

            var intializeSessionCounter = function () {
                $scope.sessionTime();
                $interval(function () {
                    $scope.sessionCounter--;
                    if ($scope.sessionCounter > 1) {
                        console.log('timedown', $scope.sessionCounter);
                    }
                    else {
                        $scope.showSessionTimeoutWarningModal();
                        $scope.stop();


                    }
                }, 1000);
            }
            intializeSessionCounter();

Above everything is working fine as it goes through the if statement. When $scope.sessionCounter goes to 1 I hit the else statement. The modal that I want to open pops up. Next $scope.stop is hit and $interval.cancel(null) is read. However, nothing cancels and my modal continues to reopen as $interval continues to run into negative numbers.

            $scope.stop = function () {
                $interval.cancel(null);
            }

Upvotes: 0

Views: 513

Answers (1)

Saebyeok
Saebyeok

Reputation: 124

You have to bind $interval provider to some variable.

try this :

$scope.sessionCounter = 5;

var intializeSessionCounter = function () {
      $scope.sessionTime();
      $scope.interval = $interval(function () {
          $scope.sessionCounter--;
          if ($scope.sessionCounter > 1) {
              console.log('timedown', $scope.sessionCounter);
          }
          else {
              $scope.showSessionTimeoutWarningModal();
              $scope.stop();
          }
      }, 1000);
}
intializeSessionCounter();

... 
$scope.stop = function () {
    if( $scope.interval !== undefined){
        $interval.cancel($scope.interval);
        $scope.interval = undefined;
    }        

}

Upvotes: 1

Related Questions