Typorithm · medium

setTimeout in a Loop

settimeout-loop-outputinterview-questionsevent-loopclosuresvar-let
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn setTimeout in a Loop

0%

Tricky Output

A var loop shares ONE function-scoped binding, so setTimeout callbacks all read the final value (3, 3, 3). Switching to let gives each iteration its own binding, so the callbacks print 0, 1, 2.

setTimeout callbacks run after the synchronous loop has finished. With var, there is a single function-scoped i, so by the time any callback runs i has already reached 3 — every callback logs 3.

let is block-scoped and creates a brand-new binding on each iteration, so each closure captures the value i had during that iteration: 0, then 1, then 2.

Before let, the classic fix was an IIFE that copied the current value into a new scope, e.g. (function (k) { setTimeout(() => console.log(k)); })(i).

01

var loop + setTimeout logs 3, 3, 3.

02

let gives each iteration its own binding → 0, 1, 2.

03

Callbacks run after the loop, reading the final shared value.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0); // logs 3, 3, 3
}

for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 0); // logs 0, 1, 2
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Function-scoped var

var has one shared, function-scoped binding for i across every iteration of the loop.

for (var i = 0; i < 3; i++) {

2. All see the final i

Each callback closes over the same i and runs after the loop ends, when i is already 3.

setTimeout(() => console.log(i), 0); // logs 3, 3, 3

3. Block-scoped let

let creates a fresh j binding for each iteration, so each closure captures a different value.

for (let j = 0; j < 3; j++) {

4. Per-iteration binding

Because each iteration has its own j, the callbacks print 0, 1, and 2.

setTimeout(() => console.log(j), 0); // logs 0, 1, 2

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

setTimeout in a Loop: Lesson & Practice · Typorithm | ApplyDjinn