Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  164] [ 2]  / answers: 1 / hits: 21365  / 12 Years ago, thu, november 1, 2012, 12:00:00

Possible Duplicate:

setTimeout in a for-loop and pass i as value






for (var i = 0; i < 5; i++) {
setTimeout(function (i) {
console.log(this.i)
}, 1000);
}


This prints 5 five times. How can I write the loop so that it prints 0, 1, 2, 3, 4?


More From » javascript

 Answers
63

Wrap it in a self-executing closure:



for (var i = 0; i < 5; i++) (function(i) {
setTimeout(function() {
console.log(i)
}, 1000);
})(i);


Note: the argument to the function-expression to setTimeout is not being used, so I took that out. Also, it's not good to use global variables. Create variables using the var keyword.



You also don't need this.i; simply use i.


[#82248] Tuesday, October 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trevionbronsonr

Total Points: 160
Total Questions: 85
Total Answers: 110

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
trevionbronsonr questions
;