繁体   English   中英

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

[英]Ensure that JavaScript function gets called only if previous function finishes running

我有这个网页,该网页在加载时运行一个带有一些AJAX调用的函数( loadListItems ),以填充一个包含10个项目的列表(递归过程中有多个调用,以获取10个VALID项目)。

页面上有一个按钮,该按钮始终可见,并且该按钮用于加载列表中的其他项(接下来的10个VALID项)。 该按钮也调用loadListItems

我希望单击按钮以调用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.
   }
}

如何做到这一点?

就像您说的那样,请排队并在完成后调用它。

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]);
   }
}

这就是你想要的。 但是,请查看评论以获得更好的建议。 这不是一个好的解决方案。

暂无
暂无

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

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