0

Is foo below safe if it is called twice in quick succession such that the second call occurs before the first response is received ? If it is safe could you please explain the mechanism behind how the correct "param" value gets matched to the correct "xmlHttp" response ?

function foo (param)
{
    var xmlHttp = GetXmlHttpRequestObject();

    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        {
            // do something involving param and xmlHttp.responseXML
        }
    }

    xmlHttp.open("GET", "GetAsyncData.ashx", true);
    xmlHttp.send();
}
Funky Oordvork
  • 403
  • 4
  • 15
  • Check this out: http://stackoverflow.com/questions/15091810/ajax-not-working-in-loop/15092127#15092127 – DanC Feb 26 '13 at 15:18

2 Answers2

1

var xmlHttp is bound to the function foo scope. Each time the function is called, a new xmlHttp is set. For function parameters, the same happens. Parameters are also bound to the function scope the same way as var xmlHttp is. So, in this case, each time the function is called, the param and the xmlHttp are both variables bound to the same scope, and this is the reason why each param is going to be matched to the correct xmlHttp response.

For more insight, read about javascript closures.

DanC
  • 8,595
  • 9
  • 42
  • 64
0

var scopes a variable to a function. Each call to that function will create a new variable with that name.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335