Possible Duplicate:
Javascript closure inside loops - simple practical example
for (i = 0; i < 100; i++) {
setTimeout(function() {
console.log(i);
}, 500)
}
In the above code, it will print only 100. I know the reason. But how do i send the current i value to the callback in setTimeout
?
Use an anonymous function inside the loop to create a closure:
for (i = 0; i < 100; i++) {
(function(i){
window.setTimeout(function() {
console.log(i);
}, 500)
})(i);
}
As you are passing the value to the function when calling, the value will be copied and each instance of the function will have its own copy that doesn't change when the loop counter changes.
setTimeout accepts parameters that are passed to the callback :
for (i=0;i<100;i++){
setTimeout(function(i){
console.log(i);
},500, i)
}
This works:
for (var i = 0; i < 100; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 500);
})(i);
}
for (i = 0; i < 100; i++) {
setTimeout((function(i) {
return function(){
console.log(i);
}
})(i), 500)
}