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

367
Views
Why my interval is still counting and didn't stop at 0?

I wonder why my countdown didn't stop at 0, the "Time's Up" log are still logging infinitely.

Here's my code:

let timer = 6;
setInterval(function () {
  if (timer > 0) {
    timer--;
  console.log(timer);
  } else {
    console.log("Time's Up");
    clearInterval(timer);
  }
}, 1000);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

clearInterval needs to know the action you want to cancel. In this case, the action is actually your setInterval, so just assign it to a variable and use that variable as a parameter for clearInterval.

 const myInterval = setInterval(() => {
  if (timer > 0) {
    timer--;
  console.log(timer);
  } else {
    console.log("Time's Up");
    clearInterval(myInterval);
  }
}, 1000); 
about 4 years ago · Juan Pablo Isaza Report

0

What I understand that you are using timer as a variable. So, you are doing one mistake, you are giving wrong parameter inside clearInterval method. You can stop clearInterval method by the code written below:-

NOTE:- I just substitute console.log with document.write to show the Output on screen.

var timer = 5;
var myinterval = setInterval(function () {
    if (timer > 0) {
      timer--;
    document.write(timer+"<br>");
    } else {
      document.write("Time's Up");
      clearInterval(myinterval);
    }
  }, 1000);

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!