简体   繁体   中英

Ensure that JavaScript function gets called only if previous function finishes running

I have this webpage, which when loaded runs a function ( loadListItems ) with some AJAX calls to populate a list with 10 items (there are multiple calls in a recursive matter, in order to get 10 VALID items).

There's a button on the page, which is visible at all times, and that button is there to load additional items in the list (the next 10 VALID items). The button calls loadListItems as well.

I want the button click to call the loadListItems function, however, if the previous call of the function is not finished, I want to queue the new call, so it runs whenever it finishes.

function pageLoad() {
   loadListItems();
}

var finished = false;
function loadListItems() {
   jQuery.ajax({
            url: ...
   }).done(function (data) {
      //do stuff with the data
      if (not enough data loaded) {
          //then call again recursively
          loadListItems();
      } else {
          //we're done
          var finished = true;
      }
    });
}

function buttonHandler() {
   if (finished) {
       loadListItems()
   } else {
       //run loadListItems whenever it finishes.
   }
}

How can achieve this?

Like you said, make a queue and call it after finishing.

function pageLoad() {
   loadListItems();
}

var finished = false;
// you may just increase or decrease a number 
// but in case you need to call it with parameters, use array
var queue = [];

function loadListItems() {
   // you need to set finish flag to false whenever you start call
   finish = false;
   jQuery.ajax({
       url: ...
   }).done(function (data) {
      //do stuff with the data
      if (not enough data loaded) {
          //then call again recursively
          loadListItems();
      } else {
          // check queue
          if(queue.length > 0) {
              var params = queue.shift();
              // call with params or not
              loadListItems();
          } else {
              finished = true;
          }
      }
   });
}

function buttonHandler() {
   if (finished) {
       loadListItems()
   } else {
       //run loadListItems whenever it finishes.
       queue.push([parameters to retrieve data]);
   }
}

This is what you want. But please check comments for better advise. This is not the good solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM