Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda