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

188
Visualizações
JavaScript Why does an inner setTimeout of a Promise runs after an outside setTimeout

When run the below code snippet, it outputs 2,1. Since Promise is a micro-task and everything inside a promise should run before a macro-task (setTimeout), I expect that the output will be 1,2. So even if there is a macro-task inside a micro-task, I thought the output will be 1,2.

But it outputs 2,1.

What's the catch here? Why does it outputs 2,1 instead 1,2?

Promise.resolve().then(() => {
    setTimeout(() =>{
    console.log("1")
 }, 0)
})

setTimeout(() => {
    console.log("2")
}, 0)
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The promise is a micro task and will get executed before timeout1, but timeout1 is already scheduled as a macro task.

When the promise resolves, timeout2 will get scheduled, but the macrotask Q already has timeout1 and as such this is already scheduled and will get executed first.

about 4 years ago · Juan Pablo Isaza Relatório

0

Promise.resolve().then(/* 1. */() => {
    setTimeout(/* 4. */() => {
        console.log("1") /* 8. */
     }, 0)
    /* 5. */
})


setTimeout(/* 2. */() => {
    console.log("2") /* 6. */
    /* 7. */
}, 0)
/* 3. */

  1. The following task is added to the microtask queue. Let's call it "micro1":

    () => {
        setTimeout(() => {
            console.log("1")
        }, 0)
    }
    

    The task queues look like

    • Micro: [ micro1 ]
    • Macro: []
  2. The following macrotask is scheduled. Let's call it "macro1"

    () => {
        console.log("2")
    }
    

    The task queues look like:

    • Micro: [ micro1 ]
    • Macro: [ macro1 ]
  3. The code finishes executing. The event loop picks the next task. The Microtask queue has a priority, the next task to execute is micro1.

  4. The following macrotask is scheduled. Let's call it "macro2"

    () => {
        console.log("1")
    }
    

    The timeout is zero, therefore there is nothing to wait. The queue is first in, first out, therefore the task macro2 is added to the end. There is no higher priority just because it came from a microtask or anything like that.

    The task queues look like:

    • Micro: []
    • Macro: [ macro1, macro2 ]
  5. Task finishes executing. The event loop picks the next task. The Microtask queue is empty, therefore it picks a task from the macrotask queue. Next task to execute is macro1.

  6. The task prints "2" to the console.

  7. Task finishes executing. The event loop picks the next task. The Microtask queue is empty, therefore it picks a task from the macrotask queue. Next task to execute is macro2.

  8. The task prints "1" to the console.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is the Eventloop (best Explenation I have ever seen): https://youtu.be/cCOL7MC4Pl0?t=487

console.log("1")
Promise.resolve().then(() => {
    console.log("4")
    setTimeout(() =>{
        console.log("7")
 }, 0)
    console.log("5")
})
console.log("2")
setTimeout(() => {
    console.log("6")
}, 0)
console.log("3")

The snipped might help you understand it

Promis.resolve().then() does the same as setTimout(0) so you basically write a timeout inside a timout and thus the eventloop has to loop over it twice

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