How do you fix the setTimeout loop closure bug in JavaScript?
Use let instead of var in the for loop. let creates a fresh binding per iteration, so each callback closes over its own i. With var, all callbacks share one i, which is the final value by the time they run.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Closures in Callbacks and Event Handlers in JavaScript
Yes. Every callback function closes over the variables from where it was defined. setTimeout callbacks, event listeners, fetch.then, and map/filter/reduce callbacks are all closures.
Because the callback is a closure. It was defined in a scope where those variables existed, so it holds a reference to that lexical environment. When it runs later, it can still access them.
The listener function closes over variables from where it was defined. For example, a click handler can close over a count variable and increment it on each click. The closed-over state persists across events.
Still have questions?
Browse all our FAQs or reach out to our support team
