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

179
Visualizações
Javascript timer/counter crashing browser

This code is meant to start a timer when you type something into the text input, that will count every second until it reaches 5 seconds, and then stop. But it keeps spitting out 0 which is creating an endless while loop that crashes the browser. I'm sure I'm missing something obvious here :-/ !?

var secondsPassed = 0;

function setTimer() {
  
  while (secondsPassed <= 5) {
    console.log(secondsPassed);
    setInterval(function() { secondsPassed += 1; }, 1000);
  }
}
<input type="text" onkeyup="setTimer()">

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's the wrong way to both set the interval and count time.

I recommend something on the lines of:

var secondsPassed = 0, timerOn = false;
function setTimer(){
   if(timerOn) return;
   var t0 = Date.now();
   timerOn = true;
   var intervalId = setInterval(
       function(){ 
          secondsPassed = Math.round((Date.now()-t0)/1000);
          console.log(secondsPassed)
          if(secondsPassed >= 10){
              clearInterval(intervalId);
              timerOn = false;
          }
       }, 1000
   );
}
<input type="text" onkeyup="setTimer()">

I stopped the timer after 10 seconds, for the case someone wants to test it, but of course, you'll have to stop it otherwise.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your while loop will never stop because its condition (secondsPassed <= 5) will never evaluate to true, since setInterval isn't synchronous.

You should instead move the condition inside the setInterval.

var secondsPassed = 0;

function setTimer() {
  var interval = setInterval(function() {
    if (++secondsPassed == 5) clearInterval(interval);
    console.log(secondsPassed)
  }, 1000);
}
<input type="text" onkeyup="setTimer()">

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