Is there a way to run a function if jQuery's $.ajax function hits it's timeout
?
i.e.
$.ajax({ ... ... ,timeout:1000(){do something if timeout) ... });
The default value is 0 , which means there is no timeout.
In Ajax functions many callback functions exist. For example, when the request is raised, one function will raise one event when the request is successfully finished, again another function will be fired. This is the most important and heavily used functions of jQuery Ajax functions.
This can be achieved by using jQuery setTimeout() function. This function executes the given Ajax code after some amount of given time.
$.ajax({ ... timeout: 1000, error: function(jqXHR, textStatus, errorThrown) { if(textStatus==="timeout") { //do something on timeout } } });
For more information check out the jQuery documentation:
http://api.jquery.com/jQuery.ajax/
Edited
It's been over a year since I initially answered this and the textStatus
possible values have changed to "success", "notmodified", "error", "timeout", "abort",
or"parsererror"
. For error callbacks, only the last four statuses are possible.
Also you can now wire your error handlers through the returned JQuery deferred promise object's .fail
method:
var promise = $.ajax({ timeout: 1000 }); promise.fail(function(jqXHR, textStatus) { if(textStatus==="timeout") { // handle timeout } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With