Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

405
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda