循环ajax调用,直到按钮被按下

Looping ajax calls until button is pressed

本文关键字:按钮 ajax 调用 循环      更新时间:2023-09-26
document.getElementById("uploadUpdate").addEventListener("click", function() {
    intervalVarUpload = setInterval(function () {
        console.log("Updating table..");
        Object.keys(arrExplores).forEach(function (key) {
            if(arrExplores[key][2] != "Not"){
                //remoteArrUpdate makes a ajax call
                remoteArrUpdate(arrExplores[key][2], key);
            }
        });
    }, 2000);
    console.log("Interval started!");
});

document.getElementById("uploadStop").addEventListener("click", function() {
    clearInterval(intervalVarUpload);
});

function remoteArrUpdate(id, key) {
    $.ajax({
        url: 'https://offcloud.com/api/remote/status',
        data: {'requestId' : id},
        type: 'POST',
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            arrExplores[key] = [arrExplores[key][0],key,data.status.requestId,data.status.status, data.status.fileSize];
             explorArrToTable();
        },
        error: function() {
            console.log('Failed!');
        }
    });
}

此时,uploadUpdate按钮被点击,间隔开始遍历数组,对每个对象进行ajax操作并更新该对象。但是,我不想使用间隔,因为有时下一个间隔将在前一个间隔完成之前开始,有时会有很长的等待时间。我希望下一个间隔在前一个间隔成功或不成功地完成所有ajax调用后立即开始,再次从数组的开头开始并开始进行相同的ajax调用,直到按下uploadStop按钮。我该如何改变两个按钮功能来做到这一点?

只是试图模仿你的ajax调用使用setTimeout。您可以在ajax成功/失败中使用它。我认为,你需要一些代码重构来实现这一点。希望这篇文章能帮助你找到正确的方向。

var intervalVarUpload;
document.getElementById("uploadUpdate").addEventListener("click", function() {
  uploadUpdate();
});
function uploadUpdate() {
  //Start the Interval
  intervalVarUpload = setInterval(doSomething, 2000);
  console.log("Interval started!");
}
document.getElementById("uploadStop").addEventListener("click", function() {
  console.log("Interval Stopped");
  //Clear the Interval
  clearInterval(intervalVarUpload);
});
function doSomething() {
  //Clear the Interval so as to hold on till the current method call is complete.
  clearInterval(intervalVarUpload);
  console.log("Updating table..");
  var arrExplores = {
    customArray: ["Yes", "Not", "Hello"]
  };
  Object.keys(arrExplores).forEach(function(key) {
    if (arrExplores[key][2] != "Not") {
      //remoteArrUpdate makes a json call
      remoteArrUpdate(arrExplores[key][2], key);
    }
  });
}
function remoteArrUpdate(id, key) {
  setTimeout(function() {
    //Consider as a ajax complete
    uploadUpdate();
  }, 2000)
}
<button id="uploadUpdate">Upload Update</button>
<button id="uploadStop">Upload Stop</button>