Answer
JavaScript is single-threaded with an event loop:
- Synchronous code runs on the call stack.
- When the stack is empty, the loop drains the microtask queue completely (Promises,
queueMicrotask,MutationObserver). - Then it takes one macrotask (
setTimeout,setInterval, I/O, UI events), runs it, and again drains all microtasks.
So microtasks always run before the next macrotask.