Does setTimeout with 0 delay run immediately in JavaScript?
No. The callback goes to the macrotask queue. The event loop runs it only after the current call stack is empty and all microtasks are done. So it runs after the synchronous loop finishes.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in setTimeout and Closures in JavaScript Explained
3, 3, 3. var is function-scoped, so all callbacks share one i. By the time the callbacks run (after the loop, via the event loop), i is 3. All three callbacks log 3.
Use let instead of var (each iteration gets a fresh binding). Or use an IIFE to capture the current value of i as a parameter. Or pass i as an extra argument to setTimeout.
Because let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. With var, all callbacks share one i.
Still have questions?
Browse all our FAQs or reach out to our support team
