简体   繁体   English

确保仅在上一个函数完成运行时调用JavaScript函数

[英]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). 我有这个网页,该网页在加载时运行一个带有一些AJAX调用的函数( loadListItems ),以填充一个包含10个项目的列表(递归过程中有多个调用,以获取10个VALID项目)。

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). 页面上有一个按钮,该按钮始终可见,并且该按钮用于加载列表中的其他项(接下来的10个VALID项)。 The button calls loadListItems as well. 该按钮也调用loadListItems

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. 我希望单击按钮以调用loadListItems函数,但是,如果该函数的上一次调用未完成,我希望将新调用排队,因此只要完成,它就会运行。

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. 这不是一个好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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