Lesson 54 of 296
The loop-with-setTimeout bug
What you will learn
- A classic interview puzzle
- Why
varprints the same number three times - Why
letfixes it - Other ways to fix it
On this page
The puzzle
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 100);
}Many people expect 0 1 2. The real output is:
3
3
3Why
Two facts combine:
setTimeoutruns its callback later. The loop finishes completely first (in a few microseconds). The callbacks run about 100ms later.varcreates only ONEifor the whole loop (it is function-scoped). All three callbacks are closures over the same variable.
By the time the callbacks run, the loop has ended and that single i is 3 (the value that made i < 3 false). All three read the same variable, so all print 3.
The fix: let
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 100);
}Output: 0 1 2.
let is block-scoped, and a for loop with let creates a new i for each iteration, initialised with the value from the previous one. Each callback closes over its own i.
Other fixes (for old code or interviews)
An IIFE (Immediately Invoked Function Expression), a function that runs as soon as it is created, giving each iteration its own scope:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 100);
})(i);
}setTimeout's extra arguments, which are passed into the callback:
for (var i = 0; i < 3; i++) {
setTimeout((j) => console.log(j), 100, i);
}bind (Lesson 56):
for (var i = 0; i < 3; i++) {
setTimeout(console.log.bind(console, i), 100);
}The same bug elsewhere
The same problem appears with event listeners created in a var loop: every button reports the last index. The fix is the same: use let, or use forEach, which gives each callback its own variables.
How to say it in an interview
"With var there is a single function-scoped i shared by all the callbacks. setTimeout callbacks run after the loop has finished, so they all read the final value, 3. With let, the for loop creates a fresh binding of i for each iteration, so each closure captures its own value and it prints 0, 1, 2. In older code you could fix it with an IIFE or by passing i as an argument to setTimeout."
Key words
| Word | Meaning |
|---|---|
| Callback | A function passed to be run later |
| Binding | The connection between a name and a value |
| Per-iteration binding | let in a for loop creating a new variable each time |
| IIFE | A function expression that runs immediately |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.