Why does my asynchronous JavaScript code inside a loop not behave as expected, and how can I fix it? [duplicate]

14 hours ago 1
ARTICLE AD BOX

Everything happens exactly as it can be expected.

This is a combination of a closure and a callback function passed to setTimeout.

The closure is created by referencing the loop variable i from the implementation of the anonimous function passed to setTimeout. It extends the lifetime of the integer object referenced by i (as if it was a static variable and not a stack variable).

Due to the delay, the function reads this variable not sooner than after 1 second since the fist iteration. By that time, the variable value becomes 5.

Read Entire Article