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

155
Vistas
when do setTimeOut callback function get its parameters?

I'm a little confused on how setTimeOut works: why the callback function didn't got the values it needed when it was invoked, but got them from the bottom of the script?

I expected it to print 5 and not 7..

what am I missing ?

any help is appreciated, thanks!

let foo = () => {
  console.log(x);
};

let x = 5;
setTimeout(foo, 0); //7
for (let i = 0; i < 10000000000; i++) {} //just to waste some time because the timeOut is actually 4ms
x = 7;

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

0

Callback function of the setTimeout isn't executed until the call stack is empty and the call stack won't be empty until the execution of your synchronous javascript code completes.

As the last statement overwrites the value of x, when the callback function of setTimeout is invoked, it logs the latest value, i.e. 7.

It seems that you are expecting the callback function of setTimeout to be executed while the for loop is executing BUT that's not how Javascript works.

Once the timer of the setTimeout expires, callback function of the setTimeout is enqueued in the task queue. From the task queue, event loop will push this callback on the call stack BUT the callback function won't be pushed on the call stack until no other javascript code is executing, i.e. the call stack is empty.

It doesn't matters how long it takes for the synchronous script execution to end; no scheduled callback will be executed until the synchronous script execution ends.

Keep in mind that all your code executes on a single thread.

Also note that the number of milliseconds passed to setTimeout is NOT the exact time after which the callback function will be executed; it's the minimum time after which the callback function will be invoked.

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