计时器在 0 后继续

Timer continues after 0

我在 JavaScript 为学校的一个项目(我还在学校,是的,我没有 JavaScript 作为本学期的一课)做了一个计时器,它在之后继续0. 我从老师那里得到了一些帮助,但我无法联系到他的流行病和其他东西。

这是我编写的代码,发生的情况是,当它到达我输入的日期时,它会进入 -0 -0 -0 -01 并从那里继续。

const countdown = () => {
    let countDate = new Date('Febuary 9, 2022 00:00:00').getTime();
    let now = new Date().getTime();
    let gap = countDate - now;

    let second = 1000;
    let minute = second * 60;
    let hour = minute * 60;
    let day = hour * 24;

    let textDay = Math.floor(gap / day);
    let textHour = Math.floor((gap % day) / hour);
    let textMinute = Math.floor((gap % hour) / minute);
    let textSecond = Math.floor((gap % minute) / second);

    document.querySelector('.day').innerText = textDay;
    document.querySelector('.hour').innerText = textHour;
    document.querySelector('.minute').innerText = textMinute;
    document.querySelector('.second').innerText = textSecond;

};

setInterval(countdown, 1000);

setInterval returns 一个值,您可以将其传递给 clearInterval 以停止从 运行 开始的间隔。将该值存储在变量中,例如:

let countInterval = 0;

const countdown = () => {
  //...
};

countInterval = setInterval(countdown, 1000);

然后 countdown 内,您可以检查是否要清除该间隔。例如,如果您想在 gap <= 0 时清除它,您将执行该逻辑:

if (gap <= 0) {
  clearInterval(countInterval);
  return;
}

当最终满足该条件时,这将停止从 运行 开始的间隔。


示例:

let countInterval = 0;

const countdown = () => {
    let countDate = new Date('January 11, 2022 13:35:00').getTime();
    let now = new Date().getTime();
    let gap = countDate - now;
    
    if (gap <= 0) {
      clearInterval(countInterval);
      return;
    }

    let second = 1000;
    let minute = second * 60;
    let hour = minute * 60;
    let day = hour * 24;

    let textDay = Math.floor(gap / day);
    let textHour = Math.floor((gap % day) / hour);
    let textMinute = Math.floor((gap % hour) / minute);
    let textSecond = Math.floor((gap % minute) / second);

    document.querySelector('.day').innerText = textDay;
    document.querySelector('.hour').innerText = textHour;
    document.querySelector('.minute').innerText = textMinute;
    document.querySelector('.second').innerText = textSecond;

};

countInterval = setInterval(countdown, 1000);
<div class="day"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>