jigar suthar’s Post

⏱️ 𝗡𝗼𝗱𝗲.𝗷𝘀 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — setTimeout 𝘃𝘀 setImmediate Many developers think setTimeout(fn, 0) runs immediately. But in Node.js, 𝗲𝘃𝗲𝗻𝘁 𝗹𝗼𝗼𝗽 𝗽𝗵𝗮𝘀𝗲𝘀 𝗱𝗲𝗰𝗶𝗱𝗲 𝘁𝗵𝗲 𝗿𝗲𝗮𝗹 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗼𝗿𝗱𝗲𝗿. Let’s understand the difference between setTimeout and setImmediate 👇 🔍 𝗖𝗼𝗿𝗲 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 setTimeout(fn, 0) • Schedules callback in 𝗧𝗶𝗺𝗲𝗿𝘀 𝗣𝗵𝗮𝘀𝗲 • Executes 𝗮𝗳𝘁𝗲𝗿 𝘁𝗶𝗺𝗲𝗿 𝘁𝗵𝗿𝗲𝘀𝗵𝗼𝗹𝗱 𝗶𝘀 𝗿𝗲𝗮𝗰𝗵𝗲𝗱 • Not truly immediate setImmediate(fn) • Schedules callback in 𝗖𝗵𝗲𝗰𝗸 𝗣𝗵𝗮𝘀𝗲 • Executes 𝗿𝗶𝗴𝗵𝘁 𝗮𝗳𝘁𝗲𝗿 𝗣𝗼𝗹𝗹 𝗣𝗵𝗮𝘀𝗲 • Designed to run 𝘪𝘮𝘮𝘦𝘥𝘪𝘢𝘵𝘦𝘭𝘺 𝘢𝘧𝘵𝘦𝘳 𝘐/𝘖 🧠 Example: const fs = require('fs'); fs.readFile(__filename, () => {   setTimeout(() => {     console.log('timeout');   }, 0);   setImmediate(() => {     console.log('immediate');   }); }); ⚙️ 𝗪𝗵𝗮𝘁 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆? 1. fs.readFile registers an 𝗜/𝗢 𝗼𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻 2. When file read completes → callback enters 𝗣𝗼𝗹𝗹 𝗣𝗵𝗮𝘀𝗲 3. Inside callback:• setImmediate → scheduled in 𝗖𝗵𝗲𝗰𝗸 𝗣𝗵𝗮𝘀𝗲 • setTimeout(0) → scheduled in 𝗧𝗶𝗺𝗲𝗿𝘀 𝗣𝗵𝗮𝘀𝗲 4. The event loop continues… ➡ After Poll Phase → 𝗖𝗵𝗲𝗰𝗸 𝗣𝗵𝗮𝘀𝗲 𝗿𝘂𝗻𝘀 𝗳𝗶𝗿𝘀𝘁 ➡ Then next iteration → 𝗧𝗶𝗺𝗲𝗿𝘀 𝗣𝗵𝗮𝘀𝗲 𝗿𝘂𝗻𝘀 🏁 𝗢𝘂𝘁𝗽𝘂𝘁 immediate timeout And this order is 𝗰𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝘁 𝗶𝗻 𝘁𝗵𝗶𝘀 𝘀𝗰𝗲𝗻𝗮𝗿𝗶𝗼 because: • setImmediate runs right after I/O (Check phase) • setTimeout waits for next Timers phase 𝗜𝗳 𝘁𝗵𝗶𝘀 𝗵𝗲𝗹𝗽𝗲𝗱 𝘆𝗼𝘂 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗡𝗼𝗱𝗲 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝘀 𝗯𝗲𝘁𝘁𝗲𝗿, 𝗹𝗲𝘁’𝘀 𝗰𝗼𝗻𝗻𝗲𝗰𝘁. 🤝 #NodeJS #JavaScript #EventLoop #Backend #AsyncProgramming #SystemDesign #Programming

It’s worth noting for readers that the reason setTimeout(fn, 0) is inconsistent in the main script is because it depends on the performance of the process—if the loop enters the Timers phase in less than 1ms, it might miss the timer and hit setImmediate first. Using an I/O callback like fs.readFile as you did is the only way to guarantee setImmediate wins every time. Solid post!

To view or add a comment, sign in

Explore content categories