Javascript 停止倒计时

Javascript stop countdown

我在 js 中有一个倒计时,我无法添加我想要的技巧。

当计数结束时,它并没有停止。负数开始,相反,我希望它在时间到期后停止在 0。我怎么能?

  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 1000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("countdown").innerHTML = hours +  " ore "  + minutes +  " min "   + seconds +  "  sec";
  }

改变这个:

if (count == -1) {
  clearInterval(counter);
  return;
}

为此:

if (count < 0) {
  clearInterval(counter);
  localStorage.removeItem('count');
  return;
}

总是让你的条件尽可能严格,或者 。您实际上并不关心它是否等于 -1。你关心它低于 0.

在您的原始代码中,当页面在没有 localStorage 的情况下加载时它停止正常。但最后,您将 localStorage 设置为 -1。刷新时,将其设置为 -2 (count - 1) 并启动计数器进入负数。您的条件永远不会根据存储的 -1 值进行检查。

问题是您将 count-1 值放在 LocalStorage 中。

count = setLocalStorage('count', count - 1);

在页面重新加载后,您一直从 -1 中减去 1,得到 -2,这是您的条件 count == -1 无法捕捉到的。解决方案是在检查是否需要继续计时器后,将下一个计数值放入 LocalStorage 中。

<script type="text/javascript">

  let count = 0;
  let counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = Number(getLocalStorage('count')) || 5;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
     window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    const nextCount = count - 1
    if (nextCount < 0) {
      clearInterval(counter);
      return;
    }
    count = setLocalStorage('count', nextCount);

    const seconds = count % 60;
    let minutes = Math.floor(count / 60);
    let hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours +  " ore "  + minutes +  " min "   + seconds +  "  sec";
  }
 </script>

<div id="timer"></div>

希望对您有所帮助:)