Preventing new ajax request while the old one is running

I am trying to write a function that fetches data from the server on a scroll. I would need to write a function like this ...

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

      

Right now I'm a little confused about how to check the old call .ajax()

. so i can undo the new one. I am confused because every time the function is called, how can I check the previous call status. Can I access the variables of the previous call?

+3


source to share


2 answers


$.ajax()

returns a promise that the attribute provides readyState

, so you can just assign the return value $.ajax()

call the variable and check itreadyState

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

      



Then the ajax call will only fire if the previous one is executed ( readyState == 4

).

+1


source


You can set the flag like this:



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

      

+1


source







All Articles