简体   繁体   中英

Can a callback to a finished XmlHttpRequest trigger before the send-function is complete?

I just noticed some weird behavior on a webapp i have after installing Firefox 11. I have not seen this error before and the site has been running for over a year.

var timeOutTimer = null;

var StartDownload = function () {
    xhr.open("GET", "/Download", true);           //Notice asynchronous=true
    xhr.onreadystatechange = DownloadComplete;
    xhr.send("...");

    timeOutTimer = new Timer(......);   //This line gets executed AFTER DownloadComplete()
};

var DownloadComplete = function () {
    if (xhr.readyState == 4) {
        timeOutTimer.Abort();           //<--------timeOutTimer is null here
        //Callstack points back to xhr.send
    }
}

Should it really be possible for XmlHttpRequest to call the onreadystatechange-callback before even exiting the send()-function?

This error only occurs when i browse the website on my local development-server. Also, if i add a 1sec-delay serverside there is no problem. I have not tried in any other browsers.

I guess that the solution would be to start the timer before the send but i just want to know the reason behind this behavior and if it is ok since i have never experienced it before.

you say "before even exiting the send() function" but that's not really true. you're calling send and then you're constructing a timer, but things are happening so fast that before you even get the timer into its variable, the callback happens. it's asynchronous, just like you asked for. just need to be prepared for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM