JavaScript runs one piece of code at a time: events wait in queues rather than interrupting execution. When the current code finishes, the event loop processes queued work. section 8.1.4
Callback timing depends on which queue holds the work:
- Promise callbacks run asynchronously, even when the promise is already settled. section 8.1.4
- Promise callbacks use the microtask queue; setTimeout callbacks use the task, or macrotask, queue. Microtasks take priority over macrotasks. section 8.1.4
- setTimeout(callback, 0) does not mean immediate execution; the HTML Living Standard specifies a minimum delay of 4 milliseconds. section 8.1.4
Listing 8.6 Queueing callbacks with setTimeout and then
setTimeout(() => {
console.log("setTimeout callback");
}, 0);
Promise.resolve(true).then(() => {
console.log("then callback");
});
console.log("end of script");
In this example, the script logs first, the promise's then callback follows, and the setTimeout callback runs last. section 8.1.4













