Search code examples
javascriptxmlhttprequestdom-eventsanonymous-methods

Passing arguments to anonymous Javascript functions


Consider the code below:

this.usedIds = 0;

this.SendData = function(data)
{
    var id = this.usedIds;
    this.usedIds++;

    this.xmlHttpThing.open("POST", "/Upload.aspx", true);
    this.xmlHttpThing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    var currentObject = this;
    this.xmlHttpThing.onreadystatechange = function() { currentObject.UploadComplete(id) };
    this.xmlHttpThing.send(data);
};
this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {
        //First time id is 0
        //Second time id is 0                 <<<--------- Why??
        //Third time id is 1
        //Fourth time id is 2
        //Fifth time id is 3 ....         

        this.SendData("blabla");
    }
};

Why does the id I pass to the anonymous function get delayed by one call after the first call?

Only seems to be this way in Firefox, in IE the UploadComplete receive the ids in the correct order.

In the second loop I can stop the debugger at the send(data)-line and confirm that the id is actually 1 but when I get to the UploadComplete it turns out to be 0 in that argument :(

EDIT: Found solution:
Disable Console-logging in FireBug.


Solution

  • Disabling the Console-logging in Firebug solved the problem!