循环ajax调用直到按下按钮

时间:2016-10-18 04:23:13

标签: javascript json ajax

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按钮。我如何更改两个按钮功能来执行此操作?

1 个答案:

答案 0 :(得分:0)

尝试使用setTimeout模仿你的ajax调用。你可以在你的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>