Stop timer at zero

时间:2019-04-23 15:06:37

标签: javascript function clearinterval

I am trying to get my countdown to stop at zero however it resets rather than stops.

I've added a conditional statement at the end of the runTimer function but nothing happens. It just resets.

I'm going off of an exercise where it counts up. I'm modifying it a bit and having it countdown.

function runTimer() {
    let currentTime = leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
    theTimer.innerHTML = currentTime;
    timer[3]--;

    timer[0] = Math.floor((timer[3]/100)/60); //minutes
    timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60)); //seconds
    timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000)); //hundredths

    if (currentTime = 0) {
      clearInterval(interval);
    }

}

I expected it to stop at zero but it just resets back to 59:00... and I want it to stop at 00:00.

2 个答案:

答案 0 :(得分:2)

The problem is this part:

if (currentTime = 0)

Since you're checking if the value is 0, you don't want to assign a value of 0, instead you want to compare currentTime with 0. This is done with the === operator. So to summarize:

= is to assign a value to a variable. ( left is variable and right is the assignment)

== or === is to compare the two values.(Difference between == and === in JavaScript)

Your line should be:

if (currentTime == 0)

Hope it helped. :)

答案 1 :(得分:1)

两点。

1)如前所述,您的if子句将不起作用,因为您使用的是“ =”(单个等号)。 JavaScript中的单个等号执行 assign 值,而不执行 compare 值。但是,您需要比较值,并且需要使用双精度或三重等于。

2)即使您进行了更改,currentTime也可能永远不会取值为零,因为您之前已经为currentTime分配了一个字符串。因此,即使currentTime为"00:00",该字符串也不会计算为0(参见图片)

enter image description here

我想您更想做这样的事情:

if (timer[2] === 0 && timer [1] === 0 && timer[0] === 0) {
    clearInterval(interval);
}

或者最有可能满足以下条件:

if (timer[3] <= 0) {
    clearInterval(interval);
}