Frontend Development 5 min read

Why Does setTimeout Print 0 1 2 3 3 3? Unraveling Async, Scope, and Closures

An in‑depth look at a common interview puzzle that prints “0 1 2 3 3 3”, explaining how JavaScript’s asynchronous setTimeout, function scope, and closures interact, why the output occurs, and how to modify the code to achieve the expected 0‑1‑2 sequence.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Why Does setTimeout Print 0 1 2 3 3 3? Unraveling Async, Scope, and Closures

Result: 0 1 2 3 3 3. This interview question tests many concepts.

Key topics: asynchronous execution, scope, and closures.

Simplified example: first prints 2 then 1 because setTimeout is asynchronous.

setTimeout takes two arguments: a function and a delay. When called, the function is placed in the event queue and executed after the main program finishes, similar to binding an event to a button.

setTimeout’s delay works like a “meeting that never arrives on time”: after the specified time (e.g., 2000 ms) the callback is queued; if the queue is empty it runs immediately, otherwise it waits.

The program does not error and prints 1 because when console.log(i) runs, the preceding var i = 1 has already completed.

In ES5 there is no block‑level scope, so the loop variable i is accessible outside the loop. ES6 introduced let to create block scope.

The original problem uses a for loop to avoid repetitive code. Rewriting the loop shows why the output is 0 1 2 3 3 3.

Because setTimeout registers callbacks, we can adjust the code to make it print 0, 1, 2 by creating a new closure for each iteration.

One solution is to wrap the setTimeout call in an IIFE (immediately‑invoked function expression) that captures the current value of i.

Another solution is to use let in the loop, which gives each iteration its own block‑scoped i.

JavaScriptasynchronousClosureES6setTimeoutScopeES5
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.