[ACCEPTED]-How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?-browser

Accepted answer
Score: 60

Some of the modern browsers (2012) do this 2 without having to rely on setTimeout: it's included 1 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);
Score: 53

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 7 IE8, You can add a timeout event handler to the 6 XMLHttpRequest object.

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

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

More Related questions