Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Javascript counter not stopping

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);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
   }
   ...
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!