CS Fundamentals Trainer · Guides
The JavaScript event loop: tasks, microtasks and why order surprises people
One thread, a call stack, a task queue and a microtask queue: how setTimeout, promises, async/await and queueMicrotask are ordered, why a long synchronous loop freezes a page, and how to yield without breaking things - with every output in this guide produced by running it in Node.
4 min read
JavaScript runs your code on one thread. There is no parallel execution of two functions of yours at the same time, and yet a page can fetch data, animate and respond to clicks. The trick is the event loop: a single thread that runs one piece of code to completion, then picks the next piece of work from a queue. Most "why did this print in that order" questions are questions about which queue a piece of work was in.
The pieces
- Call stack. The function that is running now and the ones that called it. Code on the stack runs to completion; nothing interrupts it.
- Task queue (also "macrotask" queue). Work scheduled by timers (
setTimeout), I/O callbacks, UI events and messages. The loop takes one task, runs it, then does the next step below. - Microtask queue. Promise reactions (
.then,.catch,.finally, and the continuation after anawait) andqueueMicrotask. After the current task (and after every callback that leaves the stack empty) the engine drains the whole microtask queue before it takes the next task, including microtasks that were added while draining.
The rule that explains most orderings: synchronous code first, then all microtasks, then the next task.
console.log('1 sync');
setTimeout(() => console.log('4 timeout'), 0);
Promise.resolve().then(() => console.log('3 microtask'));
console.log('2 sync');
Running this prints 1 sync, 2 sync, 3 microtask, 4 timeout. The timeout has a delay of 0 but it is still a task, so it waits until the microtask queue is empty.
async/await is promises with nicer syntax
An await pauses the async function and schedules the rest of it as a microtask when the awaited promise settles. The code before the first await runs synchronously.
async function f() {
console.log('f start');
await null;
console.log('f after await');
}
f();
console.log('after call');
This prints f start, after call, f after await. Calling f() returns as soon as it reaches the await, so the caller continues first.
Microtasks can starve everything else
Because the loop drains the microtask queue completely, a microtask that keeps adding microtasks never lets a task run. The same is true of a long synchronous loop: nothing else, including rendering in a browser, can happen until it ends.
let n = 0;
function again() { if (++n < 5) queueMicrotask(again); }
setTimeout(() => console.log('timeout ran after', n, 'microtasks'), 0);
again();
The output is timeout ran after 5 microtasks: all five chained microtasks ran before the timer's task got a turn. With a million chained microtasks the timer would wait for all of them.
Timers are "no sooner than", not "exactly at"
setTimeout(fn, 100) means "put fn in the task queue after at least 100 ms". If the thread is busy, it runs later. Browsers also clamp nested timers (about 4 ms after several levels), and background tabs throttle them. Never use a timer as a precise clock; compare performance.now() or Date.now() instead.
Keeping a page responsive
A long computation blocks input and painting. Options, from simplest:
- Split the work into chunks and yield between them with
setTimeout(next, 0)(a task, so rendering and events can run in between) - not withPromise.resolve(), which is a microtask and does not let the browser paint. - Move it off the thread: a Web Worker in the browser,
worker_threadsin Node. - Do less: debounce input handlers, virtualise long lists, avoid re-computing what has not changed.
In browsers, requestAnimationFrame callbacks run just before a repaint, which makes them the right place for visual updates, and requestIdleCallback is for low-priority work.
Node.js specifics
Node has the same two queues with extra phases (timers, poll for I/O, setImmediate in the "check" phase). Two facts matter in practice:
process.nextTickcallbacks run before promise microtasks, after the current operation.- From inside an I/O callback,
setImmediatealways runs before asetTimeout(…, 0). From the main module the order of those two is not guaranteed.
Errors
A thrown error inside a .then callback rejects the next promise in the chain; inside an async function it rejects the returned promise. An unhandled rejection is reported by the runtime (Node terminates the process by default since v15). Always await inside try/catch or attach .catch, and remember that a rejection inside a setTimeout callback is not caught by a try/catch around the call that scheduled it, because that code has already left the stack.
A checklist for ordering questions
- Write down the synchronous statements in order. That is the first output.
- Collect the promise reactions and
awaitcontinuations that were queued, in the order they were queued. They run next, as one batch, plus any they add. - Then take timers and I/O in order of readiness.
- If the answer depends on exact timing between a timer and I/O, the honest answer is "do not depend on it".
Sources
- HTML Standard: event loops — the specification of tasks and microtasks.
- Node.js: The Node.js Event Loop — phases,
nextTickandsetImmediate. - MDN: Using microtasks in JavaScript with queueMicrotask().
Practise this topic: JavaScript JavaScript › Concurrency