簡體   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