The Event Loop
See how the call stack, task queue, microtask queue and rendering interleave, and why long tasks freeze the UI.
Intermediate · about 3 hours · difficulty 3/5
Learn first: Asynchronous JavaScript: Callbacks, Promises and async/await
The event loop explains when your code actually runs. It turns confusing ordering bugs into predictable behaviour and is a favourite interview topic.
The pieces
- Call stack: the function currently executing and the ones that called it. JavaScript runs one stack frame at a time.
- Web APIs: timers, network, DOM events run outside the JS engine and queue callbacks when done.
- Task (macrotask) queue:
setTimeout,setInterval, I/O and UI event callbacks. - Microtask queue: promise reactions (
.then, code afterawait) andqueueMicrotask. It has priority.
The loop, simplified
- Run one task to completion.
- Drain all microtasks (including ones queued by other microtasks).
- If it is time, render (style, layout, paint), running
requestAnimationFramecallbacks first. - Repeat.
So console.log("A"); setTimeout(() => console.log("B")); Promise.resolve().then(() => console.log("C")); console.log("D"); prints A, D, C, B.
Why it matters in practice
- A long synchronous task (heavy loop, big JSON parse) blocks input and rendering. Anything over 50ms is a "long task" and hurts Interaction to Next Paint.
- Break up work with
setTimeout,scheduler.yield()where supported, or move it to a Web Worker. - Use
requestAnimationFramefor visual updates so they line up with frames. - An infinite chain of microtasks can starve rendering completely.
Move on when you can predict the log order of mixed timers, promises and awaits, and you can spot a long task in the Performance panel.
Key concepts
- Call stack
- Task queue
- Microtask queue
- Rendering steps and requestAnimationFrame
- Long tasks and main-thread blocking
- Yielding to the main thread
- Node.js event loop differences
Mini project
Create an interactive demo page where buttons trigger a blocking loop, a chunked loop and a worker-free yielding version, with a spinning CSS animation and a counter showing which approach keeps the UI responsive.
Check yourself
In what order do a setTimeout(0) callback and a resolved promise's then callback run, and why?
Free resources
- Event loop: microtasks and macrotasks (javascript.info)
- What the heck is the event loop anyway? (Philip Roberts) (JSConf EU)