ben
ben

Reputation: 661

How can I detect if a jquery ajax request has been going on for more than 5 seconds

Is it possible to tell if a jquery ajax request has been going on for more than a certain length of time? I would like to prompt users of my site if the request has been going on for 10 seconds to reload and retry, but I cant find anything in the documentation to meet my request.

Upvotes: 0

Views: 709

Answers (3)

Adrian Salazar
Adrian Salazar

Reputation: 5319

So for all ajax requests in your site... you should do something like this...

$.ajaxSetup({
     beforeSend: function(jqXHR, settings){

          /* Generate a timer for the request */
          jqXHR.timer = setTimeout(function(){

               /* Ask the user to confirm */
               if(confirm(settings.url + ' is taking too long. Cancel request?')){
                   jqXHR.abort();
               }
          }, 10000);
     }
});

Upvotes: 2

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try setting timeout property and get the error handler parameter. The possible values are

"timeout", "error", "abort", and "parsererror"

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});​

Upvotes: 5

Hayley
Hayley

Reputation: 3218

Set a timeout and then cancel it once it ajax call completes.

var timer = setTimeout(function() {
    alert('Too long!');
}, 10000);

$.getJSON(url, function() {
   clearTimeout(timer);
});

Upvotes: 1

Related Questions