如何倒数并设定倒数开始时间?

时间:2019-05-22 07:51:33

标签: javascript timer local-storage countdown

此JS脚本从零开始执行递增计数。相反,我希望JS脚本从设置的时间(hh.mm.ss)开始倒数。请我应该改变什么?该脚本必须保留localStorage和ID startTime。

<div id="display-area"></div>
var timer;
var startTime;

function start() {
  startTime = parseInt(localStorage.getItem('startTime') || Date.now());
  localStorage.setItem('startTime', startTime);
  timer = setInterval(clockTick, 100);
}

function clockTick() {
  var currentTime = Date.now(),
    timeElapsed = new Date(currentTime - startTime),
    hours = timeElapsed.getUTCHours(),
    mins = timeElapsed.getUTCMinutes(),
    secs = timeElapsed.getUTCSeconds(),
    ms = timeElapsed.getUTCMilliseconds(),
    display = document.getElementById("display-area");

  display.innerHTML =
    (hours > 9 ? hours : "0" + hours) + ":" +
    (mins > 9 ? mins : "0" + mins) + ":" +
    (secs > 9 ? secs : "0" + secs);
};
start();

计时器可以工作,但是应该从设置的时间开始倒计时。

1 个答案:

答案 0 :(得分:0)

您可以通过扩展clockTick()的计算来实现倒数计时器,这样timeElapsed的计算方式为“开始时间,减去自倒数开始以来经过的时间”

通过将countdownDuration引入为currentTime - startTime,我们可以生成一个coutdown计时器,该计时器从startTime开始递减计数:

countdownDuration = currentTime - startTime
timeElapsed = startTime - countdownDuration

可以将其介绍给您的代码,如下所示:

function clockTick() {
      const currentTime = Date.now(),
        countdownDuration = currentTime - startTime,
        timeElapsed = new Date(startTime - countdownDuration),
        hours = timeElapsed.getUTCHours(),
        mins = timeElapsed.getUTCMinutes(),
        secs = timeElapsed.getUTCSeconds(),
        ms = timeElapsed.getUTCMilliseconds(),
        display = document.getElementById("display-area");

      display.innerHTML =
        (hours > 9 ? hours : "0" + hours) + ":" +
        (mins > 9 ? mins : "0" + mins) + ":" +
        (secs > 9 ? secs : "0" + secs);
};