Discover various ways to set and detect timeouts using both old and new approaches in jQuery.
See Live Demo
Utilizing Promise in jQuery 1.8+
Promise.resolve(
$.ajax({
url: '/getData',
timeout:3000 //set a 3 second timeout
})
).then(function(){
//perform an action
}).catch(function(e) {
if(e.statusText == 'timeout')
{
alert('Native Promise: Action failed due to timeout');
//handle the situation, possibly retrying
}
});
Using jQuery 1.8+
$.ajax({
url: '/getData',
timeout:3000 //set a 3 second timeout
}).done(function(){
//perform an action
}).fail(function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Action failed due to timeout');
//handle the situation, possibly retrying
}
});
For jQuery <= 1.7.2
$.ajax({
url: '/getData',
error: function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Action failed due to timeout');
//handle the situation, possibly retrying
}
},
success: function(){
//perform an action
},
timeout:3000 //set a 3 second timeout
});
Note that the textStatus parameter (or jqXHR.statusText) can indicate the cause of the failure, helpful for identifying timeouts specifically.
error(jqXHR, textStatus, errorThrown)
A function to be called upon request failure. It receives three arguments: The jqXHR (XMLHttpRequest in jQuery 1.4.x) object, a description of the type of error, and an optional exception object. Possible values for the second argument (besides null) include "timeout", "error", "abort", and "parsererror". For HTTP errors, errorThrown provides details like "Not Found" or "Internal Server Error." Starting from jQuery 1.5, multiple functions can be specified for the error setting. Each will execute sequentially. Note: This handler does not apply to cross-domain script and JSONP requests.
Source: http://api.jquery.com/jQuery.ajax/