JavaScript Gotcha: Using "let" in setTimeout Loop

JavaScript Gotcha #3: The setTimeout Loop That Lied to Me While building an animation sequence, I needed to log a series of numbers with delays using the setTimeout function. So I wrote the code in the picture expecting output as "1, 2, 3, 4, 5" but it printed "6, 6, 6, 6, 6, 6". Classic JavaScript. After a brief (and mandatory) panic, I realised the problem: "var" is function-scoped, not block-scoped. So by the time the timeouts executed, the loop had already finished, and "i" was 6. Here's the simple fix: Use "let", which is block-scoped and preserves the correct value for each iteration, and now it works perfectly. Lesson learned: When using async callbacks inside loops, scope matters. "let" doesn’t just fix bugs — it saves your sanity.

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories