Skip to content

⚑ Event Loop in Browser JS vs Node.js

  • 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.
  • 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 uses libuv under the hood, and has extra phases in its event loop.

  • Event Loop Phases in Node:

    • Timer Phase - Executes setTimeout & setInterval
    • Pending Callbacks - Executes I/O callbacks.
    • Idle, Prepare - Internal use.
    • Poll Phase - Retrives new I/O events.
    • Check Phase - Executes setImmediate
    • Close Callbacks - Closes connection.
  • πŸ’‘ Node also has:

    • Microtasks -> Promise.then, queueMicrotask
    • process.nextTick -> Runs before microtask after every phase.
  • 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).
FeatureBrowser JSNode.js
MicrotasksPromise.then, queueMicrotaskSame
MacrotaskssetTimeout, setIntervalsetTimeout, setInterval, setImmediate
Special Queue❌ Noneβœ… process.nextTick (higher priority than microtasks)
Order of async tasksMicrotasks β†’ Macrotasksprocess.nextTick β†’ Microtasks β†’ Macrotasks
Event loop phasesSimplerMultiple phases (timers, poll, check, close, etc.)
  • β€œIn Browser” : Microtasks(Promises, callbacks) always run before macrotask(timers, setImmediate)
  • β€œIn Nodejs” : process.nextTick runs first, then Promises (microtasks), then timers and setImmediate depending on the phase.”