25

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)
...

});
d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • 2
    Maybe what you want: http://stackoverflow.com/questions/3543683/jquery-ajax-timeout-setting – Eli May 14 '13 at 00:44

1 Answers1

48
$.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  
    }
});
Dan-Nolan
  • 6,594
  • 4
  • 27
  • 32
  • 5
    Usually, good answers are explained, rather than just dropping a block of code. – Daedalus May 14 '13 at 00:44
  • 1
    @Paulpro I wouldn't agree. It isn't explained what is passed to the error function, other than a string that would sometimes equal 'timeout'. – Daedalus May 14 '13 at 00:45
  • 1
    Worth mentioning: "The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to **time out before it can be sent**." In this case, only the `complete` handler is called: neither the `success` or `error` handlers seem to run. – aaaidan Nov 25 '14 at 09:43