2

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);
        });
    }
Teshan N.
  • 2,307
  • 3
  • 30
  • 59
  • I notice a lot of the duplicates suggested tend to ask the question from a different direction or different level of known knowledge; ie, those questions already know the issue is something to do with closures. – Katana314 Oct 10 '13 at 17:47

1 Answers1

9

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

Community
  • 1
  • 1
Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134
  • Will this alert in the order from 1 to 5? – Teshan N. Oct 10 '13 at 17:56
  • No, that will depend on when the callback function is triggered. If the second call arrive first, it'll call 2 before 1. At this point, the flow is not controlled by the loop, but by the asynchronous action. If you need these callback to be triggered in order, then checkout async flow library like Async.js or the Promise specs (jQuery has a promise implementation built-in you can use too). – Simon Boudrias Oct 10 '13 at 18:10