Since your calls are asynchronous, callbacks are not executed until all of the above lines have been run. This means that the parameter will be set to 2 before your first receive request is resolved.
Create unique names for your variables, such as param1, param2, instead of just reassigning the parameter.
Edit:
Check this code:
for (var i = 0 ; i < 3; i++) { param = i; $.get('http://www.google.com',genCallback(param)); param = i+5; } function genCallback(param) { var cb = function (data) { alert(param); } return cb; }
Honestly, I'm not quite sure how this works. You will notice that it notifies the number 0, 1, 2 in some order, although I am constantly changing the parameters. Instead of creating an anonymous function in get directly, I create a function based on a parameter. I think the closure is created over cb , which includes the local genCallback parameter at the time it is executed.
source share