Node.js setTimeout vs setImmediate vs process.nextTick explained

Day 50/50 – JavaScript Interview Question? Question: What is the difference between setTimeout(), setImmediate(), and process.nextTick() in Node.js? Simple Answer: setTimeout() schedules callback in macrotask queue after delay. setImmediate() executes in next event loop iteration. process.nextTick() executes before next phase (microtask, highest priority). Order: nextTick() → Promises → setImmediate() → setTimeout(). 🧠 Why it matters in real projects: Understanding these is crucial for Node.js performance, avoiding event loop starvation, and controlling async execution order. Misusing them causes performance bottlenecks or unexpected behavior. 💡 One common mistake: Overusing process.nextTick() starves the event loop since it runs before I/O. Also assuming setImmediate() runs immediately—it's actually next iteration, and order with setTimeout(0) can vary. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: setTimeout'), 0); setImmediate(() => console.log('3: setImmediate')); process.nextTick(() => console.log('4: nextTick')); Promise.resolve().then(() => console.log('5: Promise')); console.log('6: End'); // Output: // 1: Start // 6: End // 4: nextTick (highest priority) // 5: Promise (microtask) // 3: setImmediate (next loop) // 2: setTimeout (timer phase) // Use cases: // nextTick - let constructor complete class AsyncResource { constructor() { process.nextTick(() => this.init()); } } // setImmediate - break up long operations function processLargeArray(arr) { const chunk = arr.splice(0, 100); processChunk(chunk); if (arr.length > 0) { setImmediate(() => processLargeArray(arr)); // ✓ Yields } } // Danger: Recursive nextTick starves I/O! function dangerous() { process.nextTick(dangerous); // ✗ Infinite, blocks I/O } // Better: use setImmediate for recursion function better() { setImmediate(better); // ✓ Allows I/O } // Modern alternative to nextTick Promise.resolve().then(() => { // Microtask like nextTick, less aggressive }); 🎉 Series Complete! 50/50 JavaScript Interview Questions #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #NodeJS #EventLoop #AsyncProgramming #WebDev #SeriesComplete

To view or add a comment, sign in

Explore content categories