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

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);

Leave a Comment