Why is my AngularJS undo interval not working

I would like to stop the countdown when I press the stop timer. I do not know why this does not work. I have a simple jsfiddle created here .

CODE
View

<div ng-app="timerApp" ng-controller="timerController">
    <h4>Time Remaining: {{countdown}}</h4>
    <button ng-click="startTimer()">Start Timer</button>
    <button ng-click="stopTimer()">Stop Timer</button>
</div>

controller

angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval', function ($scope, $interval) {
    var timer;
    var time = 10;
    $scope.countdown = time;

    $scope.stopTimer = function() {
        $interval.cancel(timer);
    };

    $scope.startTimer = function() {
        timer = $interval(function() {
           $scope.countdown--;
        }, 1000, time).then(function() {
            $scope.countdown = time;
        });
    };

}]);
+4
source share
1 answer

The problem is the call thenreturns a new promise than the one that returns $interval, which is required by the method$interval.cancel()

angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
  function($scope, $interval) {
    var timer;
    var time = 10;
    $scope.countdown = time;

    $scope.stopTimer = function() {
      $interval.cancel(timer);
    };

    $scope.startTimer = function() {
      timer = $interval(function() {
        $scope.countdown--;
      }, 1000, time);
      timer.then(function() {
        $scope.countdown = time;
      });
    };

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="timerApp" ng-controller="timerController">
  <h4>Time Remaining: {{countdown}}</h4>
  <button ng-click="startTimer()">Start Timer</button>
  <button ng-click="stopTimer()">Stop Timer</button>
</div>
Run code
+12
source

Source: https://habr.com/ru/post/1613762/


All Articles