β‘ Event Loop in Browser JS vs Node.js
πΉ Common Concepts (Both)
Section titled βπΉ Common Concepts (Both)β- Call Stack -> Executes functions (LIFO).
- Web/Node APIβs -> Handle async works (timers, HTTP, events).
- Task Queues -> Where async callbacks go before execution.
- Event loop -> Decided when to move tasks from queues into the stacks.
πΉ Browser JavaScript (Chrome, Firefox, etc.)
Section titled βπΉ Browser JavaScript (Chrome, Firefox, etc.)β- Macrotasks (Task Queues) :
setTimeout,setInterval, DOM events,setImmediate(not in browser)
- Microtasks (Job Queues) :
Promise.then,queueMicrotask, MutationObserver.
- Priority Rule:
- After each stack execution β run all microtasks β then move on to one macrotask.
console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End");
// β
Output (Browser): Start End Promise Timeout- π Promise (microtask) runs before setTimeout (macrotask).
πΉ Node.js Event Loop
Section titled βπΉ Node.js Event Loopβ-
Node.js uses
libuvunder the hood, and has extra phases in its event loop. -
Event Loop Phases in Node:
- Timer Phase - Executes
setTimeout&setInterval - Pending Callbacks - Executes
I/Ocallbacks. - Idle, Prepare - Internal use.
- Poll Phase - Retrives new I/O events.
- Check Phase - Executes
setImmediate - Close Callbacks - Closes connection.
- Timer Phase - Executes
-
π‘ Node also has:
- Microtasks ->
Promise.then,queueMicrotask - process.nextTick -> Runs before microtask after every phase.
- Microtasks ->
-
Priority in Node.js :
- process.nextTick
- Microtasks (Promises, callbacks)
- Macrotasks (timers, setImmediate, etc)
-
Example in Nodejs ->
setTimeout(() => console.log("Timeout"), 0); setImmediate(() => console.log("Immediate")); Promise.resolve().then(() => console.log("Promise")); process.nextTick(() => console.log("NextTick"));
// β
Output (Node.js):
NextTick Promise Timeout Immediate- π Explanation:
process.nextTickβ highest priority.- Then
Promise.then(microtask). - Then
setTimeout(timer phase). - Then
setImmediate(check phase).
β‘ Key Differences: Browser vs Node.js
Section titled ββ‘ Key Differences: Browser vs Node.jsβ| Feature | Browser JS | Node.js |
|---|---|---|
| Microtasks | Promise.then, queueMicrotask | Same |
| Macrotasks | setTimeout, setInterval | setTimeout, setInterval, setImmediate |
| Special Queue | β None | β
process.nextTick (higher priority than microtasks) |
| Order of async tasks | Microtasks β Macrotasks | process.nextTick β Microtasks β Macrotasks |
| Event loop phases | Simpler | Multiple phases (timers, poll, check, close, etc.) |
π§ Interview One-liners
Section titled βπ§ Interview One-linersβ- βIn Browserβ : Microtasks(Promises, callbacks) always run before macrotask(timers, setImmediate)
- βIn Nodejsβ :
process.nextTickruns first, thenPromises(microtasks), thentimersandsetImmediatedepending on the phase.β