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

190
Vistas
Why does recursive/nested `setTimeout` does not stop execution without an `else` statement?

I am learning to use recursive setTimeout function.

My task is to create a function that takes 2 number arguments, from and to and prints each number in between to the console, one at the time with the delay of 1 second in between.

My question is, why function printNumbers1 does not stop execution after printing number 4 to the console? The assumption is that the timerID is incorrect, but I do not understand why.

const DELAY = 1000;

const printNumbers1 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;

    if (counter > to) clearTimeout(timerID);

    // the function not stop the invocation without the `else` statement
    timerID = setTimeout(run, DELAY);
  }, DELAY)
}

const printNumbers2 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;
    if (counter > to) clearTimeout(timerID);
    else {
      timerID = setTimeout(run, DELAY);
    }
  }, DELAY)
}

printNumbers1(1, 4); // continues to execute after 4th invocation
printNumbers2(1, 4); // stops execution after 4th invocation

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

That's because in the first code block, the execution continues, setTimeout is called again and it sets timerID another value.

After counter > to condition is satisfied, you need to stop the execution or prevent the next line (which calls setTimeout again) to be executed. That's why the second code block is correct.

When you call clearTimeout, it just clears the previously set timer but does not stop the execution of the rest of the code block (which includes calling another setTimeout in the next code line).

about 4 years ago · Juan Pablo Isaza Denunciar

0

Thanks for the clarifications @Zafer, @Teemu.

Now, it's clear that I should have either stopped the execution in my if statement like this:

const printNumbers1 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run(){
    console.log(counter);
    counter++;

    if(counter > to) return;    
    timerID = setTimeout(run, DELAY);
  }, DELAY)
}

or, as @Teemu suggested, invoke the recursive function only if the condition is satisfied like this:

const printNumbers1 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run(){
    console.log(counter);
    counter++;
    
    if(counter <= to) timerID = setTimeout(run, DELAY);
  }, DELAY)
}
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