Reputation: 6685
var count = 0;
for ( var i = 0; i < 4; i++ ) {
setTimeout(function(){
assert( i == count++, "Check the value of i." );
}, i * 200);
}
Why doesnt this work(i
comes equal to 4 rather than equal to count every time)? count, var
are created in a global scope so why would they not be available inside the function?
(I would like an explanation as to why this doesn't work, I found a way to get it to work by wrapping it in another function, just wanting to understand)
Upvotes: 2
Views: 2690
Reputation: 23208
Use this; Value of i will be 4 inside each setTime out as for loop already finished and value of
Anonymous function will preserve variable inside it by creating new context.
var count = 0;
for ( var i = 0; i < 4; i++ ) {
(function(i){
setTimeout(function(){
assert( i == count++, "Check the value of i." );
}, i * 200);
})(i);
}
Upvotes: 6