I have this Javascript code, which works as expected:
The variable i will always refer to the current value of i (not the value of i when called) in this situation.
i
That's how scope works in JavaScript.
See the answer by @Esailija for a solution.