Skip to content
Advertisement

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)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement