setInterval和clearInterval通过按钮单击事件

时间:2017-03-01 23:17:02

标签: javascript timer

这是我的代码:

window.onload = runThis;
function runThis() {

  const txtMin = document.getElementsByClassName("min");
  const txtSec = document.getElementsByClassName("sec");

  function go() {
    setInterval(countDown, 1000);
  }

  function countDown() {
    timeNow = timeNow - 1;
    timeSec = timeNow % 60; //remainder as seconds
    timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes

    txtMin[0].innerText =
      (timeMin > 0 ? 
        (timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
      : "00:");

    txtSec[0].innerText =
      (timeSec > 0 ? 
        (timeSec >= 10 ? timeSec : `0${timeSec}`)
      : "00");
  }

  function stopIt() {
    let x = setInterval(countDown, 1000);
    clearInterval(x);
  }

  const btnStart = document.getElementsByClassName("start");
  btnStart[0].addEventListener("click", go);

  const btnStop = document.getElementsByClassName("stop");
  btnStop[0].addEventListener("click", stopIt);
}

我在尝试设置setInterval和clearInterval时遇到问题。 2个按钮:startstop。我希望在单击go启动计时器时运行函数start。这一切都很好。我的问题是试图阻止计时器。

如果我将let x = setInterval(countDown, 1000);放在stopIt()函数之外,它会自动启动windows.onload上的计时器,无论我是否点击start按钮,所以,我可以停止计时器。

如果我将let x = setInterval(countDown, 1000);放在stopIt()函数中,就像我在这里一样,我可以随时点击start按钮启动计时器,但现在我可以' t使用clearInterval()停止计时器。

非常感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:2)

尝试在“stopIt”函数中设置外部变量中“go”函数中的间隔ID,如下所示:

window.onload = runThis;
function runThis() {
  var intervalID = null;
  const txtMin = document.getElementsByClassName("min");
  const txtSec = document.getElementsByClassName("sec");

  function go() {
    intervalID = setInterval(countDown, 1000);
  }

  function countDown() {
    timeNow = timeNow - 1;
    timeSec = timeNow % 60; //remainder as seconds
    timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes

    txtMin[0].innerText =
      (timeMin > 0 ? 
        (timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
      : "00:");

    txtSec[0].innerText =
      (timeSec > 0 ? 
        (timeSec >= 10 ? timeSec : `0${timeSec}`)
      : "00");
  }

  function stopIt() {
    clearInterval(intervalID);
  }

  const btnStart = document.getElementsByClassName("start");
  btnStart[0].addEventListener("click", go);

  const btnStop = document.getElementsByClassName("stop");
  btnStop[0].addEventListener("click", stopIt);
}