I need to do the following task. But this always alerts only "5" instead of 1,2,3,4 and 5. How can I fix this? Please help.
for(var x=1; x<=5; x++){
something.load(function(result){
alert(x);
});
}
I need to do the following task. But this always alerts only "5" instead of 1,2,3,4 and 5. How can I fix this? Please help.
for(var x=1; x<=5; x++){
something.load(function(result){
alert(x);
});
}
This is due to closure. When the callback is runned, it will alert the variable in its current state (so after the loop).
To fix this, you can create a new closure which'll keep the variable state.
for(var x=1; x<=5; x++){
(function(x) {
something.load(function(result){
alert(x);
});
}(x));
}
For a more complete explanation of Closure, you can refer to this SO question: How do JavaScript closures work?
Or this article by a member of TC39 (EcmaScript standard body) http://www.2ality.com/2013/05/quirk-closures.html