Full answer
Two separate ideas are tested.
Closures and loops:
- var is function scoped. There is one i. The callbacks run after the loop ended, when i is 3. Output: var 3, three times.
- let is block scoped, and a for loop creates a fresh binding for each iteration. Each callback keeps its own j. Output: let 0, let 1, let 2.
Timer order:
- Node clamps a delay of 0 (or less than 1) to 1 ms. So setTimeout(fn, 0) and setTimeout(fn, 1) are the same.
- Timers with the same delay are kept in a list in creation order and run in that order.
- The var and let callbacks (1 ms each, created first), then '1 ms', then '0 ms', all belong to the same group, so they print in creation order. The 10 ms timer runs later.
- The delay is a minimum, not a promise. If the process is busy, callbacks run late, but the order of timers that are due stays by due time and then by creation.
Final order: var 3, var 3, var 3, let 0, let 1, let 2, 1 ms, 0 ms, 10 ms.
A frequent follow-up asks how to fix the var version without let: use an IIFE, bind, or pass the value as an extra argument to setTimeout (setTimeout(fn, 0, i)).
javascript
for (var i = 0; i < 3; i++) setTimeout(() => console.log('var', i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log('let', j), 0);
setTimeout(() => console.log('10 ms'), 10);
setTimeout(() => console.log('1 ms'), 1);
setTimeout(() => console.log('0 ms'), 0);The output shows the closure results first and then the timers in the order they were created, with 10 ms last. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): var 3 var 3 var 3 let 0 let 1 let 2 1 ms 0 ms 10 ms
Key points
- var shares one binding; let creates one per iteration.
- A 0 ms delay becomes 1 ms in Node.
- Equal delays run in creation order.
- A delay is a minimum, not an exact time.
Common mistakes
- Expecting var to print 0, 1, 2.
- Expecting the 0 ms timer to run before the 1 ms timer.
- Thinking that a delay is exact.
- Using setTimeout order to coordinate work.
Follow-ups
- How do you fix the var loop without using let?
- What does setTimeout(fn, 0, i) do?
- How is setImmediate different from a 0 ms timer?
Tips
- Split the answer in two: closures and timer order.
- Give the fix for the var case.
- Say that timers are minimums.