Possible Duplicate:
Javascript closure inside loops – simple practical example
Seen many posts talking about setTimeout and closures but I’m still not able to pass in a simple for loop counter.
for (i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, Math.floor(Math.random() * 1000));
}
Gives
5
5
5
5
5
Would like to have
0
1
2
3
4
What’s wrong ?
Please don’t flame, I thought I have understood the setTimeout() tale but apparently not.
You can use a closure to keep a reference to the current value of
iwithin the loop:However, this is unlikely to print the numbers in order since you use a random timeout (you could use
i * 1000instead to make the numbers print in ascending order, one second apart).Here’s a working example.