Search code examples
javascripttimerlocal-storagecountdown

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


This JS script performs a progressive count starting from zero. Instead I would like the JS script to count down from a set time (hh.mm.ss). Please what should I change? The script must keep localStorage and the 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();

The timer works but should count down from a set time.


Solution

  • You can achieve a countdown timer by extending the clockTick() calculation so that timeElapsed as calculated as "start time, minus the amount of time that's passed since the countdown began".

    By introducing countdownDuration as currentTime - startTime, we can then produce a coutdown timer that counts down from startTime by:

    countdownDuration = currentTime - startTime
    timeElapsed = startTime - countdownDuration
    

    This can be introduced to your code as follows:

    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);
    };