Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping JS variable doesn't show the correct value inside the function [duplicate]

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);
        });
    }
like image 844
Teshan Nanayakkara Avatar asked Apr 30 '26 13:04

Teshan Nanayakkara


1 Answers

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

like image 176
Simon Boudrias Avatar answered May 02 '26 02:05

Simon Boudrias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!