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

232
Vistas
Get returned items from function inside setTimeout in Javascript

So I need a little delay in my JavaScript for a function inside a loop that should get called every 500 ms:

function myFunc(num) {
    return num++;
}

var theNum = 0;

while (theNum != 10) {
    theNum = setTimeout(myFunc(theNum), 500);
}
console.log("All done");

However, All done never gets logged.

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

0

  1. You're calling the function immediately. You need to pass the function reference to the setTimeout instead.

  2. And you're also creating an infinite loop due to that issue.

  3. Even if you corrected this problem "All done" would still be logged first before any of the timeouts completed.

So you need to rethink the approach. Put the timeout in a function and if theNum is less that 10 call the function again with the incremented number (setTimeout allows you to pass in arguments after the delay). Log "All done" when the count reaches 10.

function myFunc(num) {
  return `Number: ${num}`;
}

function loop(theNum = 0) {
  if (theNum < 10) {
    console.log(myFunc(theNum));
    setTimeout(loop, 500, ++theNum);
  } else {
    console.log("All done");
  }
}

loop();

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