spraff
spraff

Reputation: 33405

How to catch all terminations of XMLHttpRequest

I have an condition which has to hold before and after an XMLHttpRequest usage, but not during. Example:

var running = false; // condition

function go (callback)
{
    running = true; // condition broken

    var http = new XMLHttpRequest ();
    http .open ("GET", url, true);
    http .onreadystatechange = function ()
    {
        if (4 == this .readyState)
        {
            try
            {
                callback (this .responseText);
            }
            catch (e) {}

            running = false; // condition restored
        }
    }
}

I need to guarantee that running will always eventually become false, regardless of how the XMLHttpRequest plays out.

Is this sufficient or do I need to check some other eventualities?

Upvotes: 1

Views: 153

Answers (1)

Piotr Kochański
Piotr Kochański

Reputation: 22672

It looks like that this check is enough (http://www.w3.org/TR/XMLHttpRequest/). readyState is 4 if the data transfer has been completed or something went wrong during the transfer.

Make sure you set some reasonable value for timeout (the default is 0, that is no timeout).

Upvotes: 1

Related Questions