如何反转计数并设置倒计时开始时间?

How can I invert the count and set the countdown start time?

此 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();

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

您可以通过扩展 clockTick() 计算来实现倒数计时器,以便 timeElapsed 计算为 "start time, minus the amount of time that's passed since the countdown began".

通过将 countdownDuration 引入为 currentTime - startTime,我们可以生成一个从 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);
};