Javascript – Air XmlHttpRequest time out if remote server is offline

airjavascriptxmlhttprequest

I'm writing an AIR application that communicates with a server via XmlHttpRequest.

The problem that I'm having is that if the server is unreachable, my asynchronous XmlHttpRequest never seems to fail. My onreadystatechange handler detects the OPENED state, but nothing else.

Is there a way to make the XmlHttpRequest time out?

Do I have to do something silly like using setTimeout() to wait a while then abort() if the connection isn't established?

Edit:
Found this, but in my testing, wrapping my xmlhttprequest.send() in a try/catch block or setting a value on xmlhttprequest.timeout (or TimeOut or timeOut) doesn't have any affect.

Best Answer

With AIR, as with XHR elsewhere, you have to set a timer in JavaScript to detect connection timeouts.

var xhReq = createXMLHttpRequest();
xhReq.open("get", "infiniteLoop.phtml", true); // Server stuck in a loop.

var requestTimer = setTimeout(function() {
   xhReq.abort();
   // Handle timeout situation, e.g. Retry or inform user.
}, MAXIMUM_WAITING_TIME);

xhReq.onreadystatechange = function() {
  if (xhReq.readyState != 4)  { return; }
  clearTimeout(requestTimer);
  if (xhReq.status != 200)  {
    // Handle error, e.g. Display error message on page
    return;
  }
  var serverResponse = xhReq.responseText;  
};

Source

Related Topic