CKTIS / JavaScript
Event loop microtask checkpoints and timer tasks
In browsers, `queueMicrotask()` and Promise reactions share a microtask queue. `setTimeout()` schedules a separate task, even with a delay of `0`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
queueMicrotask(callback);
promise.then(onFulfilled, onRejected);
const timerId = setTimeout(callback, delayMs, ...args);
clearTimeout(timerId);Event loop microtask checkpoints and timer tasks explain why a microtask can run before a timer that was scheduled first. The browser may have several task queues, so tasks from different sources do not form one global FIFO queue. The event loop performs a microtask checkpoint after running a task; the browser can also perform one during script cleanup when the JavaScript execution context stack is empty. A normal return to a calling function does not trigger a checkpoint.
At a checkpoint, microtasks run in enqueue order until the queue is empty, including any added while it is draining. queueMicrotask() queues a callback directly. ECMAScript 2024 defines Promise reaction jobs; on the web, the host puts them on the same queue. For a settled promise, .then() queues the applicable reaction immediately but does not run it synchronously. For a pending promise, the reaction is queued when the promise settles.
setTimeout(callback, delayMs) queues a separate task from the timer task source after waiting. 0 means neither immediate execution nor a timing guarantee: current work and pending microtasks can delay the callback. clearTimeout(timerId) cancels the timer if its callback has not started. Timers and queueMicrotask() are host APIs, not part of ECMAScript 2024. Check availability and scheduling rules in other runtimes.
Use a microtask for brief work that should follow synchronous code. Continually adding microtasks can starve other tasks and rendering. An exception thrown by a queueMicrotask() callback is reported as uncaught; an exception thrown by a .then() handler rejects the promise returned by .then().
Examples
(() => {
const order = ["sync:start"];
setTimeout(() => {
order.push("timer");
queueMicrotask(() => {
order.push("timer:microtask");
console.log(order.join(" -> "));
});
}, 0);
queueMicrotask(() => {
order.push("microtask");
queueMicrotask(() => order.push("nested"));
});
Promise.resolve().then(() => order.push("promise"));
order.push("sync:end");
})();Result
sync:start -> sync:end -> microtask -> promise -> nested -> timer -> timer:microtask
`nested` goes to the back of the queue behind the already queued `promise`, but it still runs before `timer`. The timer task then queues its own microtask, `timer:microtask`, which prints the full expected trace.
Related lessons
- JavaScript · Lesson 16 · Intermediate · Version: 3