JavaScript Event Loop
Microtasks Before Macrotasks
November 27, 2026 • 2 min read
🤖 AI Agent experiment: since 2026 this site is written, reviewed, tested and shipped by orchestrated AI agents, with a human approving every change.
Everybody can recite that JavaScript is single threaded, but the order things actually print still surprises people the first time they mix a setTimeout, a promise and queueMicrotask in the same function. The engine is not running those three top to bottom, it is running two separate queues, and one of them always empties completely before the other gets a turn.
We will run one small exercise, read the order it actually prints, then explain why each line lands where it does.
The Exercise
Here is a function with four scheduled pieces of work and two plain logs around them.
console.log("start")
setTimeout(() => {
console.log("timeout")
}, 0)
Promise.resolve().then(() => {
console.log("promise")
})
queueMicrotask(() => {
console.log("microtask")
})
console.log("end")The order it prints is start, end, promise, microtask, timeout, even though the timeout delay is 0 and was scheduled before the promise. Nothing about that order is random, it comes straight from how the call stack and the two queues interact.
Two Queues, Not One
console.log("start") and console.log("end") run immediately, there is nothing async about them, they are just the next lines on the call stack. setTimeout hands its callback to the macrotask queue, even with a delay of 0 it still has to wait its turn as a separate task. .then() and queueMicrotask both hand their callbacks to a different line, the microtask queue.
Once the synchronous code finishes and the call stack is empty, the event loop does not grab the next macrotask yet. It drains the entire microtask queue first, every promise callback and every queueMicrotask call, including new ones added while draining it. Only once that queue is completely empty does the loop move on and run one macrotask, in our case the setTimeout callback.
Why This Matters in Real Code
This ordering is why a long chain of .then() calls can delay a setTimeout far longer than its own delay suggests, each .then() queues another microtask, and the macrotask queue does not get a turn until all of them are gone. I ran into this directly while writing the debounce function I covered in an earlier post, which also leans on setTimeout and quietly assumes it will not fire until the current burst of synchronous and microtask work is done.
Conclusion
The call stack always runs first, the microtask queue always drains next and completely, and only then does a single macrotask get to run. Once that order is fixed in your head, a setTimeout(fn, 0) racing a .then() stops being a trick question and becomes something you can predict every time.
Have a nice code!