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

407
Visualizações
Why setInterval inside a while loop become an infinite loop (JS)?

I tried to call a delayed "one" call or a "one or two?" question, but instead the function started running indefinitely, although without setInterval everything worked fine.

quester2()
function quester2() {
  for (i = 0; i <= finalCount; i++) {
    let K = Math.ceil(Math.random() * 2);
    if (K == 1) {
      setInterval(function () { console.log("one"); }, 1000);
      finalCount += 1;
      allIterations += 1;
      setInterval(function () { console.log("one or two?"); }, 1000);
    } else {
      setInterval(function () { console.log("one or two?"); }, 1000);
      allIterations += 1;
    }
  }
  console.log(finalCount);
  console.log(i);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is no infinite loop, your code may just randomly take more iterations compared to previous runs. You sometimes increase finalCount which is involved in the condition of the for loop.

What may appear like an infinite loop is the fact that you run quite a lot of setIntervals and never clear them. But if you carefully check your console you basically instantly after invoking the function see two outputs for the last two log statements. A second after that you start seeing an infinite number of "one" and "one or two?".

quester2()

0
1
one or two?

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