Closures in Action: setTimeout and Loops
The classic interview question: why does var in a loop with setTimeout print the wrong numbers, and how let fixes it.
var in a loop creates one shared variable. All setTimeout callbacks read the same i (which is 6 after the loop). let creates a new i per iteration, giving each callback its own copy.
EXERCISE
1setTimeout and Closures
setTimeout delays a function, but JavaScript does not wait for it. The delayed function forms a closure over the surrounding variables and runs later.
setTimeout takes a function and runs it later. Between the moment you hand it over and the moment it runs, the function that created it has usually returned. The callback still works because it is a closure over whatever it needed.
function delayedGreeting(name) {
const message = "Hello, " + name;
setTimeout(function () {
console.log(message);
}, 1000);
}
delayedGreeting("Ada");
delayedGreeting returns immediately, well before the second elapses. Its context is discarded, but message survives because the callback refers to it. This is the same mechanism as the previous lesson, now with a visible gap in time between creation and use.
The delay is a minimum, not a promise:
console.log("first");
setTimeout(function () {
console.log("third");
}, 0);
console.log("second");
The output is first, second, third, even with a delay of zero. The callback cannot run until the currently executing code finishes, because there is one thread and it is busy. Unit 6 covers the queue this goes through; for now the thing to hold on to is that setTimeout schedules work rather than pausing.
That gap is what makes closures over changing variables interesting, because the value can move between scheduling and running:
function show() {
var label = "before";
setTimeout(function () {
console.log(label);
}, 0);
label = "after";
}
show(); // "after"
The callback was created while label was "before" and printed "after". It captured the variable, not the value, and by the time it ran the variable had changed.
Read that example carefully, because the next exercise is the same effect at a scale that surprises almost everyone the first time. If you understand why this prints "after", you already understand the classic loop problem.
One more detail about setTimeout that matters later: it returns a handle you can use to cancel the scheduled work.
function delayedGreeting(name) {
const id = setTimeout(function () {
console.log("Hello, " + name);
}, 1000);
return function cancel() {
clearTimeout(id);
};
}
const cancel = delayedGreeting("Ada");
cancel(); // nothing is printed
cancel is itself a closure, over id. Without it there is no way to reach that timer again, because the handle was a local variable in a context that has already been discarded.
EXERCISE
2The Classic Loop Problem
This is the most famous closure interview question: using var in a loop with setTimeout prints the wrong numbers. Understanding why is the key to mastering closures.
This is the most asked closure question in interviews, and it is the previous exercise repeated five times.
function printNumbers() {
for (var i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
}
printNumbers();
The intent is 1, 2, 3, 4, 5, one per second. The output is 6, 6, 6, 6, 6.
Work out why from what you already know. var is scoped to the function, not the loop body, so there is exactly one i for all five iterations. The loop finishes in under a millisecond, leaving i at 6, which is the value that failed the condition. The five callbacks captured the variable rather than its value, so when the timers finally fire, every one of them reads the same i, and it holds 6.
Notice that the delays still work. The five lines appear one second apart, exactly as intended. Only the values are wrong, which is what makes this confusing: the part that looks hard is fine and the part that looks trivial is broken.
The fix is one keyword:
function printNumbers() {
for (let i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
}
printNumbers(); // 1, 2, 3, 4, 5
let in a for header is special-cased by the language: each iteration gets a fresh binding, initialised to the value the previous iteration ended with. Five iterations produce five separate variables, so the five closures capture five different ones.
This is worth stating precisely, because "let is block-scoped" does not quite explain it on its own. A let declared inside the loop body would also be block-scoped, but the counter lives in the header, and the per-iteration binding is a specific rule for for loops that exists largely because of this problem.
Pro Tip: When several callbacks created in a loop all report the last value, the cause is one shared binding. The question to ask is how many variables were actually created:
varin a loop creates one,letcreates one per iteration.
EXERCISE
3Fixing the Loop with var (Without Using let)
What if an interviewer asks you to fix the loop problem but you MUST use var? The trick is to create a new scope manually using a wrapper function.
let is the right fix. It is still worth knowing how the problem was solved before it existed, because the technique appears throughout older code and because it shows what let is doing underneath.
The problem is that all five callbacks share one variable. Anything that gives each iteration its own scope fixes it, and calling a function is what creates a scope.
A named wrapper makes the mechanism obvious:
function printNumbers() {
function capture(num) {
setTimeout(function () {
console.log(num);
}, num * 1000);
}
for (var i = 1; i <= 5; i++) {
capture(i);
}
}
printNumbers(); // 1, 2, 3, 4, 5
capture(i) passes the current value of i as an argument. Parameters are fresh local variables on every call, so five calls create five separate num bindings. Each callback closes over its own.
The same thing written inline is an IIFE:
function printNumbers() {
for (var i = 1; i <= 5; i++) {
(function (num) {
setTimeout(function () {
console.log(num);
}, num * 1000);
})(i);
}
}
printNumbers(); // 1, 2, 3, 4, 5
An Immediately Invoked Function Expression defines a function and calls it in the same statement. The trailing (i) is the call. It is the wrapper above with the name removed, and it does exactly the same work for exactly the same reason.
problem for (var i ...) + setTimeout one shared i, all print 6
fix 1 for (let i ...) one binding per iteration
fix 2 wrapper function called with i one parameter per call
fix 3 IIFE invoked with i the same, written inline
All three fixes do the same thing: create a new scope per iteration so each closure has something of its own to capture.
Reach for let. The other two are worth recognising when you meet them in code written before 2015, and worth understanding because they make explicit what let now does quietly.
One thing to be clear about: none of these fixes changes when the callbacks run. All five timers are still registered in the first millisecond and still fire one second apart. What changed is how many variables exist for them to read.
for (var i = 1; i <= 3; i++) {
(function (num) {
setTimeout(function () {
console.log(num, i);
}, 0);
})(i);
}
// 1 4
// 2 4
// 3 4
num differs per callback because it is a parameter of a separate call. i is the same shared variable in all three, and it reads 4 by the time they run. Both behaviours in one output, which is as direct a demonstration as the mechanism allows.
