Skip to main content

Closures Deep Dive - The Loop + setTimeout Trap

Learn Closures Deep Dive - The Loop + setTimeout Trap (JavaScript Fundamentals, JavaScript) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

The Classic var-in-a-loop Closure Bug This site's "Functions & Scope" topic already introduces closures via a counter-factory example. The single most common closure interview question builds on that idea: what happens when a closure is created inside a loop using var ? Because var is function-scoped (not block-scoped), every callback created inside the loop shares the SAME single i variable - by the time the callbacks actually run, the loop has already finished and i holds its final value.

More lessons in JavaScript Fundamentals