Cassidy
Cassidy

Reputation: 3408

How can you stop polling due to a timeout?

So I'm polling something pretty standard

(function poll(){
    $.ajax({ ... })
});

... and it works well. But now, I want to be able to continue polling every couple seconds and then if I don't get a response after two minutes, stop polling and raise an error.

How do I do the timeout?

Upvotes: 0

Views: 1794

Answers (1)

deefour
deefour

Reputation: 35360

How about something like this. Init, track, and reset the polling within the ajax promises.

var pollingTimer     = null, // stores reference to the current timer id
    firstTimeoutResponse = null; // stores the start of what might be a series of timeout responses

function poll(){
  $.ajax({
    // your options here...
  }).done(function() {
    // reset the "timeout" timer
    firstTimeoutResponse = null;
  }).fail(function(jqXHR, textStatus) {
    // if the failure wasn't a timeout, short-circuit, 
    // but only after resetting the timeout timestamp
    if (textStatus !== 'timeout') {
      firstTimeoutResponse = null;

      return;
    }

    // if it was a timeout failure, and the first one (!), init the timeout count
    if (firstTimeoutResponse = null) { 
      firstTimeoutResponse = (new Date).getTime();
    }
  }).always(function() {
    // if 2 min have passed and we haven't gotten a good response, stop polling/chort-circuit
    if ((new Date).getTime() - firstTimeoutResponse > 120000) { // 120000ms = 2min
      window.clearTimeout(pollingTimer);

      return;
    }

    // queue the next ajax call
    pollingTimer = window.setTimeout(poll, 3000); // poll every 3s
  });
}

// kick things off!
poll();

Upvotes: 1

Related Questions