5

I would like to stop the countdown when the stop timer is pressed. Im not sure why this is not working. I have a simple jsfiddle set up 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;
        });
    };

}]);
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109

1 Answers1

16

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

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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531