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

286
Vistas
How to wait for the recursive loop to finish and display the message?

I'm running a recursive function with setTimeout, what I've noticed is that javascript goes straight through the wait() function and doesn't wait for it to finish. It goes right through and leaves the wait() method working by itself.

wait(100, 30)

function wait(time, limit) {
    console.log('value >> ' + limit)
    if (limit < 0) return 'success'
    setTimeout(function () {
        wait(time, --limit)
    }, time)
}

console.log('hi')

Note that my "hi' message is at the top when running the script, because it went straight through without waiting for the recursive loop. My "hi" message should be at the end.

Can anyone help me leave the hi message at the end after running all the loop?

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

0

You could handover a function which is called at the end of waiting.

function wait(time, limit, fn) {
    console.log('value >> ' + limit)
    if (limit < 0) return fn();
    setTimeout(function () {
        wait(time, --limit, fn);
    }, time)
}

function sayHi() { console.log('hi'); }

wait(100, 30, sayHi);

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can also simply return the message which do you want:

wait(100, 30);

function wait(time, limit) {
  console.log("value >> " + limit);
  if (limit < 0) return console.log("hi");
  setTimeout(function () {
    wait(time, --limit);
  }, time);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

In addition to Nina's approach and also for use cases where a callback can not be implemented as easily as demonstrated with Nina's example code, one might use an abstraction for it, which for JavaScript is Promises.

Here, instead of 30 times delaying for 100 milliseconds until logging, one would implement wait as promise which resolves after 3 seconds with the additional logging provided as thenable ...

const wait = new Promise(resolve => setTimeout(resolve, 3000));

wait.then(() => console.log('hi'));

console.log({ wait: String(wait) });
.as-console-wrapper { min-height: 100%!important; top: 0; }

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