How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

Solution 1:

Some of the modern browsers (2012) do this without having to rely on setTimeout: it's included in the XMLHttpRequest. See answer https://stackoverflow.com/a/4958782/698168:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        alert("ready state = 4");
    }
};

xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000;
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);

Solution 2:

UPDATE: Here's an example of how you can handle a timeout:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);

xmlHttp.onreadystatechange=function(){
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      clearTimeout(xmlHttpTimeout); 
      alert(xmlHttp.responseText);
   }
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
   xmlHttp.abort();
   alert("Request timed out");
}

In IE8, You can add a timeout event handler to the XMLHttpRequest object.

var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
  alert("request timed out");
}

I would recommend against making synchronous calls as your code implies and also recommend using a javascript framework to do this. jQuery is the most popular one. It makes your code more efficient, easier to maintain and cross-browser compatible.