倒数停在0

时间:2017-01-08 09:30:57

标签: javascript angularjs intervals

尝试创建一个简单的倒计时但我希望它在计时器达到0时停止..我不知道如何实现它。

function myButton($interval) {
    return {
        templateUrl: '/templates/myButton.html',
        restrict: 'E',
        replace: true,
        scope: { },
        link: function(scope, element, attributes) {
            scope.workTime = 3;
            scope.buttonText = "Start";

            var timeSet;

            scope.countdown = function() {
                scope.workTime--;
            }
            scope.startTimer = function() {
                 if(scope.buttonText == "Reset") {
                     scope.workTime = 3;
                     $interval.cancel(timeSet);
                     scope.buttonText = "Start";
                     console.log( "test restarted");

                 } else {
                     timeSet = $interval(scope.countdown,1000);
                     scope.buttonText = "Reset";
                     console.log("test started");
                 }
            }
        }
    }

};


<div>
    <h1>{{ workTime}}</h1>
    <button ng-click="startTimer()">{{buttonText}}</button>
<div>

我尝试过if语句:

if (scope.workTimer === 0 ) {
$interval.cancel(timeSet);
}

但计时器一直保持负数。请帮忙

1 个答案:

答案 0 :(得分:0)

您应该在scope.countdown

中检查0值的条件
scope.countdown = function() {

      if(scope.workTime === 0)
      {
         $interval.cancel(timeSet);
      }
      else
      {
         scope.workTime--;
      }
  }

Plunker:https://plnkr.co/edit/uziM32Ctcb80p15HZuFd?p=preview