Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  181] [ 4]  / answers: 1 / hits: 28452  / 12 Years ago, fri, april 20, 2012, 12:00:00

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.


More From » closures

 Answers
18

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.


[#86119] Wednesday, April 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ernest

Total Points: 332
Total Questions: 92
Total Answers: 98

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;