javascript - 使用相同数据延迟对相同 URL 的 Ajax 调用

标签 javascript jquery ajax settimeout

在等待后端开发人员实现“全部取消”功能(取消后端跟踪的所有任务)时,我试图通过取消每个单独的任务来临时解决。取消 REST 服务接受数据对象形式的 ID {transferID: someID}

我使用 FOR 循环遍历存储在别处的 ID 数组。预计人们最终可能会处理数十个或数百个任务,我想实现一个小的延迟,理论上不会溢出浏览器可以处理的 HTTP 请求数量,并且还会减少后端 CPU 的负载爆炸。以下是一些带有评论的代码,用于讨论目的:

ta.api.cancel = function (taskArray, successCallback, errorCallback) {
// taskArray is ["task1","task2"]

// this is just the latest attempt. I had an attempt where I didn't bother
// with this and the results were the same. I THOUGHT there was a "back image"
// type issue so I tried to instantiate $.ajax into two different variables.
// It is not a back image issue, though, but one to do with setTimeout.
ta.xhrObjs = ta.xhrObjs || {}; 


for (var i = 0; i < taskArray.length; i++) {
    console.log(taskArray); // confirm that both task1 and task2 are there.

    var theID = taskArray[i];
    var id = {transferID: theID}; // convert to the format understood by REST

    console.log(id); // I see "task1" and then "task2" consecutively... odd,
    // because I expect to see the "inside the setTimeout" logging line next

    setTimeout(function () {
      console.log('inside the setTimeout, my id is: ')
      console.log(id.transferID);
      // "inside the setTimeout, my id is: task2" twice consecutively! Y NO task1?

      ta.xhrObjs[theID] = doCancel(id);
    }, 20 * i);
  }

  function doCancel(id) {
    // a $.Ajax call for "task2" twice, instead of "task1" then "task2" 20ms
    // later. No point debugging the Ajax (though for the record, cache is
    // false!) because the problem is already seen in the 'setTimeout' and
    // fixed by not setting a timeout.
  }
}

事情是:我知道 setTimeout 使包含函数异步执行。如果我取消超时,并在迭代器中调用 doCancel,它将在 task1 上调用它,然后在 task2 上调用它。但是,尽管它使调用异步,但我不明白为什么它只执行 task2 两次。无法理解它。

我正在寻找一种方法让迭代器以 20 毫秒的延迟进行 Ajax 调用。但我需要它来调用两者!有人看到我可以修复的明显错误,或者知道某种技术吗?

最佳答案

您必须包装函数 setTimeout 并将 id 变量传递给它,如下所示:

(function(myId, i) {
    setTimeout(function () {
        console.log('inside the setTimeout, my id is: ', myId);
    }, 20 * i);
}(theId, i));

关于javascript - 使用相同数据延迟对相同 URL 的 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538894/

相关文章:

javascript - getElementById 的替代方案 - 如何影响多个元素

javascript - 使用 ASP.NET WebForms 的 jQuery DataTables 服务器端处理

javascript - 检测图像 URL 是否损坏 JQUERY

javascript - 仅当用户接受 cookie 政策时,Google 跟踪代码管理器才会触发代码

c# - 对 ASP post 方法的 Ajax 调用不断给出 null 参数

javascript - 如何在angularJS中制作不同的ng-repeat数据部分

javascript - 无法让 JQuery 插件 Slick(旋转木马)工作

javascript - 用于保存下拉值的 session 存储

python - 如何将 Ajax 与 Django 应用程序集成?

javascript - 将错误消息传递给 ajax 错误处理程序