【问题标题】:Timer that can reset without overlapping? - Javascript可以重置而不重叠的计时器? - Javascript
【发布时间】:2020-06-20 23:11:10
【问题描述】:

对于第一次尝试将它用于学校项目的 JS,我完全是个菜鸟。

我的目标是有一个在按下按钮时倒计时的计时器。然后使用未来 10 分钟的 Unix 时间作为参数调用 countdownClock 函数。我的代码似乎运行良好,但再次按下按钮时,它会产生一个奇怪的交替故障,其中两个计时器同时运行。

如何在按下按钮时忘记前一个计时器?谢谢!


function countdownClock(time){
  // Set the date we're counting down to
  var countDownDate = (time + "000");
  // Update the count down every 1 second
  var x = setInterval(function() {
    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";
    // If the count down is over, write some text
    if (distance < 0) {
      clearInterval(x);
      document.getElementById("timer").innerHTML = "GAME OVER";
    }
  }, 1000);
}

【问题讨论】:

  • 也添加您的 html 代码,而不是我们试图猜测您的 html 代码是什么...
  • 你能不能为此创建一个jsfiddle.net,我很难理解你在做什么。或者,也添加您的 html
  • 那是因为每次点击按钮都会创建一个新作业,而之前的间隔作业只是继续工作。

标签: javascript html time timer


【解决方案1】:

我猜你是从某个地方复制的,因为它已经有你需要的东西 - clearInterval 会给你你正在寻找的结果,你应该只需要很少的改动

var intervalId;
function countdownClock(time){
  // Set the date we're counting down to
  var countDownDate = (time + "000");
  // clear the old one, if relevant
  if (intervalId)
    clearInterval(intervalId)
  intervalId = setInterval(function() {
    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";
    // If the count down is over, write some text
    if (distance < 0) {
      clearInterval(intervalId);
      document.getElementById("timer").innerHTML = "GAME OVER";
    }
  }, 1000);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2015-12-07
    • 2010-09-17
    相关资源
    最近更新 更多