setTimeout() - in for loop with random delay
closures, javascript, settimeout
Solution
You can use a closure to keep a reference to the current value of `i` within the loop:
for (i = 0; i < 5; i++) {
(function(i) {
setTimeout(function () {
console.log(i);
}, Math.floor(Math.random() * 1000));
})(i); //Pass current value into self-executing anonymous function
}
However, this is unlikely to print the numbers in order since you use a random timeout (you could use `i * 1000` instead to make the numbers print in ascending order, one second apart).
Here's a working example.
Problem
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.