The Event Loop
How single-threaded JavaScript handles concurrency — the call stack, Web APIs, the task (macrotask) queue, the microtask queue, rendering, and Node.js event loop phases — with an interactive visualiser and output-ordering puzzles.
JavaScript runs your code on a single thread: one call stack, one thing at a time. Yet a browser tab handles clicks, timers, network responses and animations "at once", and Node.js serves thousands of connections. The trick is the event loop: slow operations happen outside JavaScript (in the browser or libuv), and their callbacks are queued to run on the main thread when it's free.
The pieces
- Call stack: where synchronous code executes.
- Host APIs: the environment does the waiting (timers, sockets, file reads) on other threads or OS facilities.
- Task queue (macrotasks): callbacks from
setTimeout,setInterval, I/O, UI events,MessageChannel. - Microtask queue: promise reactions (
.then,awaitcontinuations),queueMicrotask,MutationObserver.
The algorithm
- Run the current script (itself a task) until the call stack is empty.
- Drain the microtask queue completely — including microtasks added while draining.
- (Browser) If it's time, render: run
requestAnimationFramecallbacks, style, layout, paint. - Take one task from the task queue and run it.
- Go to step 2.
The crucial rule: all microtasks run before the next task. Promises always beat setTimeout(fn, 0).
Try it
1console.log('A');2setTimeout(() => console.log('B'), 0);3Promise.resolve().then(() => console.log('C'));4queueMicrotask(() => console.log('D'));5console.log('E');
Ordering puzzles
console.log("1: script start");
setTimeout(() => console.log("2: timeout"), 0);
Promise.resolve()
.then(() => console.log("3: microtask 1"))
.then(() => console.log("4: microtask 2"));
queueMicrotask(() => console.log("5: queueMicrotask"));
console.log("6: script end");Output:
1: script start
6: script end
3: microtask 1
5: queueMicrotask
4: microtask 2
2: timeoutSynchronous code first (1, 6). Then microtasks in queue order: 3 and 5 were queued during the script; 4 is queued only when 3 finishes, so it comes after 5. Finally the timeout task.
async/await is microtasks
async function f() {
console.log("A");
await null; // everything after this is a microtask continuation
console.log("B");
}
console.log("start");
f();
console.log("end");
// start, A, end, BAn async function runs synchronously until its first await; the rest resumes as a microtask.
A harder one
setTimeout(() => console.log("t1"), 0);
setTimeout(() => {
console.log("t2");
Promise.resolve().then(() => console.log("t2 micro"));
}, 0);
setTimeout(() => console.log("t3"), 0);
Promise.resolve().then(() => console.log("m1"));
// m1, t1, t2, t2 micro, t3After each task (t2), the microtask queue is drained ("t2 micro") before the next task (t3).
Blocking the loop
While JavaScript runs, nothing else happens: no clicks, no rendering, no other callbacks.
button.onclick = () => {
const end = Date.now() + 3000;
while (Date.now() < end) {} // the page is frozen for 3 seconds
};How to keep the main thread responsive:
- Split long work into chunks and yield between them (
await scheduler.yield(), orsetTimeout(resolve, 0)). - Move CPU-heavy work to a Web Worker (a separate thread with its own event loop; communicate via
postMessage). - Use
requestAnimationFramefor visual updates andrequestIdleCallbackfor low-priority work.
Timers aren't precise
setTimeout(fn, 100) means "at least 100 ms": the callback is queued after 100 ms and runs when the stack is empty and earlier tasks are done. Browsers clamp nested timers to ≥ 4 ms and throttle timers in background tabs.
Node.js: the libuv event loop
Node uses the same model with a more detailed task loop, in phases:
Between every callback, Node drains process.nextTick callbacks first, then promise microtasks.
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
// nextTick, promise, then timeout/immediate (order of these two varies in the main module;
// inside an I/O callback, setImmediate always comes first)File system operations, DNS lookups and crypto run on libuv's thread pool (4 threads by default); network sockets use the OS's non-blocking APIs (epoll, kqueue, IOCP). See Node.js internals.
- One call stack; the host does async work and queues callbacks.
- After each task, the entire microtask queue is drained, then (in browsers) rendering may happen.
- Promises/await continuations are microtasks and run before setTimeout callbacks.
- Long synchronous work or endless microtasks block everything; chunk work or use workers.
- Node adds phases (timers, poll, check…) plus process.nextTick, which runs before promises.
QExplain the event loop.medium
JavaScript executes on one thread with a call stack. Asynchronous operations are handed to the host environment, which queues their callbacks when ready: promise reactions go to the microtask queue, timers, I/O and events to the task queue. Whenever the call stack empties, the event loop drains all microtasks, lets the browser render if needed, then runs the next task, and repeats. This gives concurrency without multithreading in user code.
QWhy does a resolved promise's then callback run before setTimeout(fn, 0)?medium
then callbacks are microtasks, setTimeout callbacks are tasks. After the current script (a task) finishes, the event loop drains the entire microtask queue before taking the next task, so all pending promise reactions run first.