Reputation: 1401
Is there a way to set the timeout period in $.get()
?
As I want my script to give a warning that loading is taking some time (perhaps due to a busy server or whatever) Can't seem to find it anywhere..
Upvotes: 17
Views: 31533
Reputation: 3335
If you want to easily display a custom error message when a timeout occurs (otherwise the $.get-completion callback is not called) you can use this:
$.ajaxSetup({
timeout: 1000,
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'timeout') {
// timeout occured
} else {
// other error occured (see errorThrown variable)
}
}
});
Upvotes: 0
Reputation: 31033
use ajaxSetup
$.ajaxSetup({
timeout:2000 // in milliseconds
});
//your get request here
Upvotes: 4
Reputation: 179086
$.get
is just a nice shorthand for $.ajax
which has a timeout
option, which will specify how long the script will wait before cancelling the callback.
You can override the global default using $.ajaxSetup({timeout: 9001})
, which will allow you to continue to use $.get
.
If you simply want to alert the user without cancelling the request, use $.ajax
, set a timeout, and cancel the timeout in the complete
callback.
Here's some example starter code, i haven't tested any of it, and it could probably be turned into a plugin with a bit of work:
(function(){
var t, delay;
delay = 1000;
$('.delay-message').ajaxStart(function () {
var $this;
$this = $(this);
t = setTimeout(function () {
$this.trigger('slowajax');
}, delay);
}).ajaxComplete(function () {
if (t) {
clearTimeout(t);
}
});
}());
$('.delay-message').on('slowajax', function () {
$(this).show().delay(2000).fadeOut(1000);
});
Upvotes: 4
Reputation: 15042
Just use .ajax()
for this; after all .get()
is just a wrapper around this. You can do something like:
function doAjax() {
var $warning = $("#warning").hide(), // Always hide to start with
warningTimeoutId = 0;
warningTimeoutId = window.setTimeout(function () {
$warning.show();
}, 10000); // wait 10s before showing warning
$.ajax({
timeout: 30000, // 30s timeout
complete: function () {
// Prevent the warning message from appearing
window.clearTimeout(warningTimeoutId);
}
... // other config
});
}
Here you start a timeout just before the Ajax call which will be shown after 10s unless the Ajax request has already finished.
Upvotes: 1
Reputation: 146310
Just use $.ajax(...)
:
$.ajax({
url: url,
success: function(data){
//...
},
timeout: 1000 //in milliseconds
});
Also as stated below in the comments you can use .ajaxSetup(...)
to apply the timeout globally:
$.ajaxSetup({timeout:1000}); //in milliseconds
Upvotes: 30