How to determine the timeout in an AJAX call (XmlHttpRequest) in a browser?

I look on the Internet, but the documentation is hard to find. We all know the basic AJAX call using the built-in browser object in XMLHttpRequest (suppose a modern browser is used here):

var xmlHttp = new XMLHttpRequest(); // Assumes native object xmlHttp.open("GET", "http://www.example.com", false); xmlHttp.send(""); var statusCode = xmlHttp.status; // Process it, and I'd love to know if the request timed out 

So, is there a way to detect that the AJAX call has completed by checking the XMLHttpRequest object in the browser? Would I be advised to do something like window.setTimeout (function () {xmlHttp.abort ()}, 30000) ;?

Thank!

-Mike

+40
javascript browser ajax
Jun 19 '09 at 15:48
source share
2 answers

UPDATE: Here is an example of how you can handle the 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 XMLHttpRequest event handler.

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

I would recommend not making synchronous calls like your code, and also recommend using the javascript framework for this. jQuery is the most popular. This makes your code more efficient, easier to maintain, and cross-browser compatible.

+48
Jun 19 '09 at 15:55
source

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

 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); 
+45
Jul 01 '13 at 7:35
source



All Articles