JavaScriptMedium
What is the Event Loop?
The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it repeatedly takes the next task from a queue, runs it to completion on the call stack, drains all microtasks, and (in browsers) lets the page render.
The pieces
- Call stack: where JavaScript actually runs, one frame at a time.
- Host APIs (browser or Node): timers, network, I/O and events run outside the JavaScript thread and queue callbacks when done.
- Task queue (macrotasks):
setTimeout,setInterval, I/O, UI events,MessageChannel. - Microtask queue: promise reactions (
.then,awaitcontinuations),queueMicrotask,MutationObserver.
One iteration of the loop
- Take the oldest task and run it until the stack is empty.
- Run all microtasks, including ones queued during this step.
- In browsers, possibly render (style, layout, paint), running
requestAnimationFramecallbacks just before. - Repeat.
Consequences
setTimeout(fn, 0)is "as soon as possible after the current task and its microtasks", never immediate.- Promise callbacks always run before the next timer.
- Long synchronous work or an endless microtask loop blocks rendering and input. Split heavy work into chunks, or move it to a Web Worker.
awaitpauses only the async function; the rest of the program keeps going.
Node.js
Node's loop has phases (timers, poll for I/O, check for setImmediate, close callbacks), and process.nextTick callbacks run even before promise microtasks.
Code example
js
1console.log("1 script start");23setTimeout(() => console.log("6 timeout (task)"), 0);45Promise.resolve()6 .then(() => console.log("4 promise 1 (microtask)"))7 .then(() => console.log("5 promise 2 (microtask)"));89queueMicrotask(() => console.log("4b queueMicrotask"));1011(async () => {12 console.log("2 async fn runs synchronously until await");13 await null;14 console.log("4c after await (microtask)");15})();1617console.log("3 script end");1819// Real output order:20// 1 script start21// 2 async fn runs synchronously until await22// 3 script end23// 4 promise 1, 4b queueMicrotask, 4c after await (microtasks, in queue order)24// 5 promise 225// 6 timeout (task)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.