whatever
whatever

Reputation: 342

preventing new ajax request while old one is in progress

I am trying to write function that fetches data from server on scroll. I will have to write a function like so...

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

I am now a bit confused as to how to check for the old .ajax() call in progress. so that I can cancel the new one. I am confused because each time the function is called how can I check the previous call status.. Can I access the variables of the previous call?

Upvotes: 3

Views: 535

Answers (2)

swornabsent
swornabsent

Reputation: 994

$.ajax() returns a promise which exposes the readyState attribute, so you could just assign the return value of your $.ajax() call to a variable and inspect its readyState

var xhr = {};
function onscrollend() {
  if(xhr.readyState === 4) {
    xhr = $.ajax({
      // ..
    });
  }
}

Then the ajax call will only fire if the previous one is done (readyState == 4).

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817030

You can set a flag like so:

var inProgress = false;
function onscrollend() {
    if (inProgress) return;
    inProgress = true;
    $.ajax(...).always(function() {
        inProgress = false;
    });
}

Upvotes: 1

Related Questions