Three timers in a loop
What does this print?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}It looks as if it should print 0, 1, 2. It prints 3, 3, 3.
Two separate facts combine to cause this. Either one alone would be harmless.
Fact 1: a function remembers variables, not values
When a function uses a variable from outside itself, it does not take a copy of the value at that moment. It keeps a link to the variable itself, and reads whatever is in it when the function finally runs.
A function together with the outside variables it holds on to is called a closure.
let count = 0;
const show = () => console.log(count);
count = 5;
show(); // 5, not 0show was created when count was 0. It prints 5, because it looks the variable up when it is called.
Fact 2: the timers run later
setTimeout(fn, 0) does not run fn immediately, even with a delay of zero. It puts fn in a queue to be run after the current code has finished. The whole loop completes first.
Put them together
1for (var i = 0; i < 3; i++) {2 setTimeout(() => console.log(i), 0);3}4// the loop has finished5// now the timers run
Variables that exist
nothing yet
Start. Press play, or step through one line at a time.
var creates a single i for the entire loop
There is one variable, and each pass changes it.
Each pass creates a function linked to that one i
Three functions, all pointing at the same variable.
The loop finishes
The last
i++makes i equal to 3, the testi < 3fails, and the loop stops.Only now do the timers run
Each one reads i. It is 3.
The functions were made at different moments, but they are all asked the same question at the same later time, about the same variable.
The fix: let
Change one word.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}1for (let i = 0; i < 3; i++) {2 setTimeout(() => console.log(i), 0);3}4// the loop has finished5// now the timers run
Variables that exist
nothing yet
Start. Press play, or step through one line at a time.
let is scoped to the block. In a for loop, JavaScript goes one step further and creates a fresh i for every pass, copying the value across. Each function is linked to its own variable, which nothing changes afterwards. The output is 0, 1, 2.
var | let | |
|---|---|---|
| Lives in | The whole function | The nearest block { } |
In a for loop | One variable shared by all passes | A new variable for each pass |
| The three timers print | 3 3 3 | 0 1 2 |
The same trap elsewhere
Any time a function is created in a loop and run later, the same thing can happen: click handlers added in a loop, callbacks for network requests, promises. Other languages have it too. Python closures in a loop behave like var:
actions = [lambda: print(i) for i in range(3)]
for action in actions:
action() # 2 2 2The cure is always the same: give each function its own variable.
Closures are useful, not just a trap
The behaviour that caused this bug is also one of the most useful things in the language. A function that remembers its surroundings can keep private state:
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2Nothing outside can touch count. Only the returned function can.
Key takeaways
- A closure is a function plus the outside variables it holds on to.
- It holds the variable itself, not a copy of its value at the time.
- With var, a loop has one variable, so every function created in it sees the final value.
- With let, each pass gets its own variable, so each function sees its own value.
- Watch for it whenever functions are created in a loop and run later.