Set timeout for ajax (jQuery)
Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.
Live Demo
Promise with jQuery 1.8+
Promise.resolve(
$.ajax({
url: '/getData',
timeout:3000 //3 second timeout
})
).then(function(){
//do something
}).catch(function(e) {
if(e.statusText == 'timeout')
{
alert('Native Promise: Failed from timeout');
//do something. Try again perhaps?
}
});
jQuery 1.8+
$.ajax({
url: '/getData',
timeout:3000 //3 second timeout
}).done(function(){
//do something
}).fail(function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
});
jQuery <= 1.7.2
$.ajax({
url: '/getData',
error: function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
},
success: function(){
//do something
},
timeout:3000 //3 second timeout
});
Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.
src: http://api.jquery.com/jQuery.ajax/
Please read the $.ajax
documentation, this is a covered topic.
$.ajax({
url: "test.html",
error: function(){
// will fire when timeout is reached
},
success: function(){
//do something
},
timeout: 3000 // sets timeout to 3 seconds
});
You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown)
option. The options are "timeout", "error", "abort", and "parsererror".