Many JavaScript beginners believe that setTimeout(fn, 0) means the function will run immediately.
But that is not true.
Let’s understand this with a very simple example and a step-by-step explanation.
📌 The Code (Quiz Question)
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
console.log("C");
❓ Question:
What will be the output?
A) A B C
B) A C B
C) B A C
D) A C
✅ Correct Answer: B) A C B
🧠 Step-by-Step Explanation (Very Important)
To understand this, you need to know how JavaScript executes code.
JavaScript has:
- Call Stack
- Task Queue (Callback Queue)
- Event Loop
Don’t worry — we’ll keep it simple.
🔹 Step 1: Synchronous Code Runs First
JavaScript executes synchronous code line by line.
console.log("A");
➡️ "A" is printed immediately.
🔹 Step 2: setTimeout is NOT Executed Immediately
setTimeout(() => {
console.log("B");
}, 0);
Even though the delay is 0, JavaScript does NOT execute this immediately.
Instead:
- The callback is sent to the Task Queue
- It waits there until the call stack is empty
❗ 0 means minimum delay, not instant execution
🔹 Step 3: Next Synchronous Line Executes
console.log("C");
➡️ "C" is printed immediately.
So far, output is:
A
C
🔹 Step 4: Event Loop Takes Control
Now:
- Call stack is empty
- Event loop checks the task queue
- Executes the
setTimeoutcallback
console.log("B");
➡️ "B" is printed last
🧾 Final Output
A
C
B
✔️ Correct option: B
⚠️ Common Mistake (Very Important)
❌ Many developers think:
setTimeout(fn, 0)= execute immediately
✅ Reality:
setTimeout(fn, 0)= execute after all synchronous code finishes
🎯 Interview Tip
If asked:
“Why does setTimeout(0) execute later?”
Say:
Because JavaScript executes synchronous code first, and
setTimeoutcallbacks are placed in the task queue and executed only after the call stack is empty.
Discover more from Learners Store
Subscribe to get the latest posts sent to your email.