categories.language Intermediate
How Does the Node.js Event Loop Work? How to Avoid Blocking?
Node.js Event Loop
Core Concept
Node.js is single-threaded but non-blocking, using the Event Loop for async I/O.
Six Event Loop Phases (in order)
- timers: Execute
setTimeout/setIntervalcallbacks - pending callbacks: Execute deferred I/O callbacks
- idle, prepare: Internal use
- poll: Retrieve new I/O events; run I/O callbacks
- check: Execute
setImmediatecallbacks - close callbacks: Run
socket.on("close")etc.
Microtasks Run Before the Next Phase
Promise.then/queueMicrotask→ highest priorityprocess.nextTick→ higher than Promise (Node.js-specific)
Execution Order
process.nextTick → Promise.then → setTimeout → setImmediate
Common Blocking Causes and Fixes
| Problem | Solution |
|---|---|
| CPU-intensive sync operations | Worker Threads / child_process |
| Large JSON parsing | Split + setImmediate to yield control |
| Synchronous fs calls | Switch to fs.readFile (async) |
Interview bonus: Explain process.nextTick vs Promise.then priority, and why overusing nextTick can starve other callbacks.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
