DEV Community

Discussion on: Improving my counter

granttransition profile image
Grant Smith Author • Edited on

Here is what I worked out; I never actually used the hours or minutes values in the HTML to start with. I was only using the seconds, calculating all the labels with that. The totalSeconds variable should account for the hours and minutes.

So here is the code I ended up with…

if (document.getElementById("counter")) {
  const hoursLabel = document.getElementById("hours");
  const minutesLabel = document.getElementById("minutes");
  const secondsLabel = document.getElementById("seconds");

    // add all the time values together to give a proper total start point
  let totalSeconds = 

  setInterval(setTime, 1000);

  function setTime() {

      // pull the number of hours out of the total for reference
     const numHours = parseInt(totalSeconds / 3600)

     //remove that number fromt he total because it messes up the /60 math if you have extra 3600's in there
     const secondsLeft = parseInt(totalSeconds - 3600 * numHours)

     // tweak these for new variables available
    secondsLabel.innerHTML = padWithZero(secondsLeft % 60);
    minutesLabel.innerHTML = padWithZero(parseInt(secondsLeft / 60));
    hoursLabel.innerHTML = padWithZero(numHours);

  function padWithZero(num) {
    return Number(num)
      .padStart(2, "0");