Javascript counter not stopping

57 Views Asked by At

for this counter I made, I used the setInterval, and when every digit is equal to zero I expect this to clear the interval, but it's not working! Can someone help me out?

const counterHTML = document.querySelector("#counter");
const timeString = localStorage.getItem("Time");

function timeToAdd(stringTime) {
  const timeArray = stringTime.split(":");
  const hoursInMiliseconds = timeArray[0] * 60 * 60 * 1000;
  const minutesInMiliseconds = timeArray[1] * 60 * 1000;
  const TIME_IN_MILISECONDS = hoursInMiliseconds + minutesInMiliseconds;
  return TIME_IN_MILISECONDS;
}

const actualTime = Date.now();
const finalTimeDateObj = new Date(actualTime + timeToAdd(timeString));
const finalTime = finalTimeDateObj.getTime();

const time = (myTimerInterval) => {
  const timeNow = Date.now();
  const diference = finalTime - timeNow;
  let displayTimeArray = msToTime(diference);
  console.log(diference);
  const hours = String(displayTimeArray[0]).padStart(2, "0");
  const minutes = String(displayTimeArray[1]).padStart(2, "0");
  const seconds = String(displayTimeArray[2]).padStart(2, "0");
  if (hours == "00" && minutes == "00" && seconds == "00") {
    clearInterval(myTimerInterval);
  }
  counterHTML.innerText = `${hours}:${minutes}:${seconds}`;
};

function msToTime(millis) {
  let h, m, s;
  h = Math.floor(millis / 1000 / 60 / 60);
  m = Math.floor((millis / 1000 / 60 / 60 - h) * 60);
  s = Math.floor(((millis / 1000 / 60 / 60 - h) * 60 - m) * 60);
  return [h, m, s];
}

var myTimerInterval = setInterval(time, 1000);
1

There are 1 best solutions below

0
UXK On

First of all I see this problem

const time = (myTimerInterval) => { 
   ...
   if (hours == "00" && minutes == "00" && seconds == "00") {
        // myTimerInterval === undefined
        clearInterval(myTimerInterval);
   }
   ...
}

The function that setInterval calls doesn't receipt any arg. myTimerInterval in this context is undefined, so clearInterval doesn't work.

Try removing that arg

const time = () => { 
   ...
   // now myTimerInterval references the global var
   if (hours == "00" && minutes == "00" && seconds == "00") {
        clearInterval(myTimerInterval);
   }
   ...
}