如何在JavaScript中编写倒数计时器?[已关闭]

只是想问如何创建最简单的倒数计时器。

网站上会有一句话说:

“注册将在05:00后关闭!”

所以,我想做的是创建一个简单的js倒数计时器,从“05:00”到“00:00”,然后在结束后重置为“05:00”。

我之前经历过一些答案,但它们似乎都太强烈了(日期对象等),对于我想做的事情来说。


答案 1

我有两个演示,一个有,一个没有。两者都不使用日期函数,并且非常简单。jQuery

使用 vanilla JavaScript 的演示

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>

使用 jQuery 的演示

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

但是,如果您想要一个更准确的计时器,而计时器只会稍微复杂一些:

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

现在我们已经制作了一些非常简单的计时器,我们可以开始考虑可重用性和分离问题。我们可以通过询问“倒数计时器应该做什么?

  • 倒计时计时器应该倒计时吗?是的
  • 倒计时计时器应该知道如何在DOM上显示自己吗?
  • 倒计时计时器是否应该知道在达到 0 时重新启动自身?
  • 倒计时计时器是否应该为客户端提供一种访问剩余时间的方法?是的

因此,考虑到这些事情,让我们写一个更好的(但仍然非常简单)CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

那么,为什么此实现比其他实现更好呢?以下是您可以对它执行的操作的一些示例。请注意,除第一个示例外,其他所有示例都无法通过函数实现。startTimer

以 XX:XX 格式显示时间并在达到 00:00 后重新启动的示例

以两种不同格式显示时间的示例

具有两个不同计时器且只有一个重新启动的示例

按下按钮时启动倒计时计时器的示例


答案 2

您可以使用 setInterval 轻松创建计时器功能。下面是可用于创建计时器的代码。

http://jsfiddle.net/ayyadurai/GXzhZ/1/

window.onload = function() {
  var minute = 5;
  var sec = 60;
  setInterval(function() {
    document.getElementById("timer").innerHTML = minute + " : " + sec;
    sec--;
    if (sec == 00) {
      minute --;
      sec = 60;
      if (minute == 0) {
        minute = 5;
      }
    }
  }, 1000);
}
Registration closes in <span id="timer">05:00<span> minutes!