简体   繁体   中英

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 = 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 I hit the else statement. 我命中了else语句。 The modal that I want to open pops up. Next is hit and is read. 被命中并且被读取。 However, nothing cancels and my modal continues to reopen as continues to run into negative numbers. 继续变为负数。

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

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;
    }        

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM