Squishy Squishy - 6 months ago 68
jQuery Question

jQuery: Pause or delay a function

So here's the situation:

I have a recursive, asynchronous AJAX call which is pulling data from the server. This recursive call happens only once when the user logs in.
I have another page which requires AJAX calls in order to navigate (basically a lazy-loaded tree). While the first AJAX call is happening, these other calls are taking a while to go through, and since the first could make as many as 2,000 requests, this delay can sometimes be fairly long.

Basically what I would like to achieve is to "pause" the recursive call when the other call is made. Pseudo code:

function recursiveAjax(){
$.ajax( {
async : true,
url : 'someurl',
dataType : 'json',
beforeSend : function(xhr) {
// do stuff
},
error : function(xhr, ajaxOptions, thrownError) {
// handle errors
},
success : function(data) {
//conditions
recursiveAjax();
}
});
}

function navigationAjax(){
$.ajax( {
async : true,
url : 'someurl',
dataType : 'json',
beforeSend : function(xhr) {
// pause recursiveAjax();
},
error : function(xhr, ajaxOptions, thrownError) {
// handle errors
},
success : function(data) {
//conditions
// resume recursiveAjax();
}
});
}

Answer

As you probably don't want the two requests at the same time, let the recursive method do one or the other. Set a flag when you want the navigation call, and let the recursive method do that request the next iteration:

var navigationCall = false;

function recursiveAjax(){
  if (navigationCall) {
    navigationCall = false;
    $.ajax( {
      async : true,
      url : 'someurl',
      dataType : 'json',
      error : function(xhr, ajaxOptions, thrownError) {
        // handle errors
      },
      success : function(data) {
        //conditions
        recursiveAjax();
      }
    });
  } else {
    $.ajax( {
      async : true,
      url : 'someurl',
      dataType : 'json',
      beforeSend : function(xhr) {
        // do stuff
      },
      error : function(xhr, ajaxOptions, thrownError) {
        // handle errors
      },
      success : function(data) {
        //conditions
        recursiveAjax();
      }
    });
  }
}

function navigationAjax(){
  navigationCall = true;
}

Note: You might want to add a window.TimeOut call to do the recursion to throttle the streams of requests to the server. There is no point in calling the server more often than the human eye can see the changes.