views:

688

answers:

3

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 anonymus 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.

A: 

I had the same problem too in the past. I don't remember exactly what caused it, but I fixed it by moving the increment to the response handler.

this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {      
        this.usedIDs++;
        this.SendData("blabla");
    }
};

Edit: after thinking about it, my case may have been different from yours. Why not increment this.usedIDs when you assign id?

var id = this.usedIDs++;
tj111
A: 

Disabling the Console-logging in Firebug solved the problem!

figures its something simple like that.
tj111
A: 

See also the question answered: How do you pass arguments to anonymous functions in javascript?

Sergey Ilinsky