How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
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.
AJAX (XmlHttpRequest) timeout length by browser
I don't think browsers have a timeout for AJAX, there is only synchronous or asynchronous requests; synchronous - first freezes the JavaScript execution until the request returns,
asynchronous - does not freeze JavaScript execution, it simply takes the request out of the execution flow, and if you have a callback function it will execute the the function in parallel with the running scripts (similar to a thread)
**sync flow:**
running JS script
|
ajax
(wait for response)
|
execute callback
|
running JS script
**async flow:**
running JS script
|
ajax --------------------
| |
running JS script execute callback
Ajax xmlhttprequest timeout
Do I need to use xmlhttprequest.timeout in case the server take too long to send the response?
No. The browser/network stack's default timeout is usually sufficient.
Does ajax consume data while waiting for the response from the server?
It is just an HTTP request and response. It takes no more bandwidth than any other request. If no data is being transferred because the server is taking time to respond, then no data is being transferred.
How to detect php server timeout on ajax request?
One strategy I used was to set a timer in JS, and then clear it if the call was successful.
var myTimer = setTimeout(stuffToDoOnFailure, 6000); // 6 secs
ajaxCall(function callBack() {
clearTimeout(myTimer);
});
EDIT:
Of course, if the ajax call succeeds after 6 secs, you might end up with both stuffToDoOnFailure
and callBack
being executed, so you want to handle that case somehow. That depends on your app, though.
Determine if $.ajax error is a timeout
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
Related Topics
What Are Alternatives to Extjs
Create a File Using JavaScript in Chrome on Client Side
Socket.Io 1.X: Use Websockets Only
What Does the at Symbol (@) Do in Es6 JavaScript? (Ecmascript 2015)
Understanding React-Redux and Mapstatetoprops()
Dynamic Variables Names in JavaScript
CSS Media Queries and Jquery Window .Width() Do Not Match
How to Remove Leading and Trailing White Spaces from a Given HTML String
Get Position/Offset of Element Relative to a Parent Container
Difference Between the JavaScript String Type and String Object
How to Ungzip (Decompress) a Nodejs Request's Module Gzip Response Body
Aggregation Filter After $Lookup
How to Replace a Regex Substring Match in JavaScript
How Dangerous Is It in JavaScript, Really, to Assume Undefined Is Not Overwritten
Simulating a Mousedown, Click, Mouseup Sequence in Tampermonkey
How to Resolve Typeerror: Cannot Convert Undefined or Null to Object