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.