倒计时停在0
Count down stop at 0
试图创建一个简单的倒计时,但我希望它在计时器到达 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);
}
但是计时器一直在倒数。请帮助
您应该在 scope.countdown
中检查 0 值的条件
scope.countdown = function() {
if(scope.workTime === 0)
{
$interval.cancel(timeSet);
}
else
{
scope.workTime--;
}
}
试图创建一个简单的倒计时,但我希望它在计时器到达 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);
}
但是计时器一直在倒数。请帮助
您应该在 scope.countdown
中检查 0 值的条件scope.countdown = function() {
if(scope.workTime === 0)
{
$interval.cancel(timeSet);
}
else
{
scope.workTime--;
}
}