Sunday, 18 November 2018

javascript - Looping JS variable doesn't show the correct value inside the function




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);
});
}

Answer




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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...