Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda