By Rahul — Google Frontend Engineer
Why JavaScript Needs an Event Loop
JavaScript is single-threaded. It can only do one thing at a time. But web apps need to handle user clicks, network responses, timers, and animations simultaneously. The event loop makes this possible by scheduling work.
Browser Event Loop
Node.js Event Loop (libuv)
Node.js has a more complex event loop with distinct phases:
Key Differences
process.nextTick() — Node.js Only
setImmediate() — Node.js Only
The Classic Puzzle
Production Impact
- Long tasks: Anything blocking the main thread for 50ms+ is a "long task" that delays user interaction. Break work into smaller chunks with
setTimeout(fn, 0)orscheduler.yield() - requestAnimationFrame: Always use for visual updates — it syncs with the render cycle
- requestIdleCallback: Run non-critical work when the browser is idle
Summary
The browser event loop: macrotask → microtasks → render → repeat. Node.js has 6 phases with microtasks between each. Understanding this determines whether your UI stays responsive and your Node.js server stays fast.