当达到某个值时如何发出警报

How do I alert when a certain value is met

所以我在 html 和 javascript 中制作了一个计时器,并在按钮上显示它。我想让它在时间值为零时提醒用户。到目前为止,这是我的代码。顺便说一句,代码是定时器代码的一部分。

      const time2=
  document.getElementById("countdown")
if(time2==0:00)
  alert("You have ran out of time, better luck next time!")

是这样的吗?

let div = document.getElementById('count')
let countdown = 10
let stopper = setInterval(myTimer, 1000)

function myTimer() {
  countdown--
  div.innerHTML = countdown + " seconds left"

  if (countdown == 0) {
    clearInterval(stopper)
  }
}
<div id='count'>10 seconds left</div>

您可以使用 setInterval() 创建一个计时器,并在达到某个值时触发一些功能,在这种情况下计时器会被清除,希望这对您有所帮助:

const createTimer = (num) => {
    const timer = setInterval(() => {
        console.log(num)
        num--;
        if(num == 0) {
            console.log("You have ran out of time, better luck next time!")
            clearInterval(timer)
        }
    }, 1000)
}
createTimer(4)

这是一个使用 class. Most important is setInterval() 的非常简单的计时器的一种可能实现方式,它允许您每 x 毫秒 运行 一个函数。

此计时器使用回调函数 onUpdate(seconds),每次更新计时器时都会调用该函数并提供剩余秒数作为参数。您当然可以对此进行扩展。

在尝试使用 DOMContentLoaded 事件访问 DOM 之前,还需要等待 HTML 文档加载。

class Timer {
  #interval;
  #initial;
  #seconds;

  constructor(seconds, onUpdate) {
    this.#initial = seconds;
    this.#seconds = seconds;
    this.onUpdate = onUpdate;
    this.onUpdate(seconds);
  }

  start() {
    this.#interval = setInterval(() => {
      this.#seconds--;
      if (this.#seconds === 0) this.stop();
      this.onUpdate(this.#seconds);
    }, 1000);
  }

  reset() {
    this.stop();
    this.#seconds = this.#initial;
    this.onUpdate(this.#seconds);
  }

  stop() {
    clearInterval(this.#interval);
    this.onUpdate(this.#seconds);
  }
}

// wait for HTML document to load
window.addEventListener("DOMContentLoaded", e => {
  const startBtn = document.getElementById("start");
  const stopBtn = document.getElementById("stop");
  const resetBtn = document.getElementById("reset");

  // create a timer and assign it seconds as well as a callback function that is called every second
  const timerDiv = document.getElementById("countdown");
  const timer = new Timer(5, (seconds) => {
    // called every seconds with seconds to go as an argument
    timerDiv.textContent = `${seconds}s to go`
  })

  // add event listeners to buttons
  startBtn.addEventListener("click", () => timer.start());
  stopBtn.addEventListener("click", () => timer.stop());
  resetBtn.addEventListener("click", () => timer.reset());
})
<div id="countdown"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>