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

340
Vistas
I am confused between JavaScript macro and micro tasks priority

I was reading about micro and macro tasks in the JavaScript stack. I wrote this code:

Promise.resolve().then(function () {
      setTimeout(function () {
        console.log('from promise one');
      }, 0);
    }).then(() => {
      console.log('from promise two');
    });

    setTimeout(function () {
      console.log('from timeout');
    }, 0);

But I realized that from timeout shows faster than from promise one in the console...

As I understood, Promise. then() is a microtask and executes before macro task which from timeout is a microtask here... but why does execute the timeout first then Promise. then?

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

0

Important things to know:

  1. setTimeout with a timeout of 0 will run the function at the beginning of the next event loop.
  2. The callback in Promise.resolve.then() is a microtask, and will be run after all of the macrotasks in the event loop have completed.

In your code, the second setTimeout runs first at the beginning of the 2nd event loop as a macrotask, then, the callback in the Promise.resolve.then() is called as a microtask, which sets a timeout for a function to be run at the beginning of the 3rd event loop.

Check out this short video for a succinct explanation of the event loop, microtasks and macrotasks, and asynchronous programming in JavaScript.

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