InterviewHubPRO
Section Overview
Q436

Question 436 of 521

Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

84%
JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

What is the difference between setTimeout, setImmediate and process.nextTick?

  1. Set Timeout: setTimeout() is to schedule execution of a one-time callback after delay milliseconds.
  2. Set Immediate: The setImmediate function is used to execute a function right after the current event loop finishes.
  3. Process NextTick: If process.nextTick() is called in a given phase, all the callbacks passed to process.nextTick() will be resolved before the event loop continues. This will block the event loop and create I/O Starvation if process.nextTick() is called recursively.

Practical Code Example

javascript
// Node.js Execution Order:
// 1. process.nextTick(): Fires immediately before event loop resumes (microtask tick)
// 2. setTimeout(fn, 0): Schedules on Timer Phase
// 3. setImmediate(fn): Schedules on Check Phase (runs after I/O callbacks)

setImmediate(() => console.log('3. setImmediate'));
setTimeout(() => console.log('2. setTimeout'), 0);
process.nextTick(() => console.log('1. nextTick'));
// Output: 1. nextTick -> 2. setTimeout -> 3. setImmediate