JavaScript SetInterval 帮助。 Ajax

标签 javascript jquery ajax

我正在尝试为我的网站编写代码

function vind(list) {
    for (i = 0; i < list.data.length; i++) {
        jQuery.ajax({
            url: 'https://xyz-abc.com/send.php?post=123',
            dataType: 'script',
            success: function () {
                volve += 1;
                if (volve >= list.data.length) {
                }
            }
        });
    }
}

所有代码都工作正常。

https://xyz-abc.com/send.php?post=123
https://xyz-abc.com/send.php?post=123
https://xyz-abc.com/send.php?post=123
https://xyz-abc.com/send.php?post=123

代码持续发布。

我想设置每个帖子之间的间隔。

https://xyz-abc.com/send.php?post=123
wait 3 sec.
https://xyz-abc.com/send.php?post=123
wait 3 sec.
https://xyz-abc.com/send.php?post=123
wait 3 sec.

我尝试了 setTimeout 不起作用。

帮助。

最佳答案

如果您首先想等待上一个请求完成,您可以发送第一项,然后使用 setTimeout 触发对列表其余部分的请求。

function vind(list) {
  if (list.length > 0) { // stop if the list is empty
    var firstItem = list.shift(); // nothing is done with this?
    jquery.ajax('https://xyz-abc.com/send.php?post=123', {
      dataType: 'script',
      success: function() {
        setTimeout(function() { // set a timeout with a function that will call sendData again
          sendData(list); // call sendData with the rest of the list
        }, 3000); // 3 seconds
      }
    });
  }
}

您可以检查该 here 的工作 plnkr .

如果您不想等待之前的请求完成,您可以使用 setTimeout 设置一组具有不同延迟的超时。不过,我不建议对大型列表执行此操作。

function sendData(item) {
  console.log(Date.now());
  jquery.ajax('https://xyz-abc.com/send.php?post=123', {
    dataType: 'script',
    success: function() {}
  });
}

function vind(list) {
  for (var i = 0; i < list.length; i++) {
    var currentItem = list[i]; // saving the item in the current scope now, in case the list gets modified in the meantime
    setTimeout(function() {
      sendData(currentItem);
    }, i * 3000); // delay depends on the item's index in the list
  }
}
以及此解决方案的工作 plnkr here .

请记住,setTimeout 并不保证 set 函数将在 3 秒标记处准确调用。它的作用是在 3 秒过去后将该函数放入回调队列中。这意味着,由于 javascript 并发的工作方式,将无法使用 setTimeout 精确地在 3 秒标记处调用函数。

您可以找到关于事件循环如何工作的非常好的解释 here 。此外,还有一个由同一个人制作的工具,可以直观地呈现幕后发生的事情 here .

关于JavaScript SetInterval 帮助。 Ajax ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789313/

相关文章:

javascript - 将节点请求模块与 AWS Lambda 和 API Gateway 结合使用

javascript - 绑定(bind)特定复选框以禁用 VueJS 中的特定下拉菜单?

javascript - 如何在 DOM 更改后检查元素是否为空?

javascript - Ajax刷新了php但没有更新

javascript - JQuery JSON 调用返回 ERR_EMPTY_RESPONSE 超时

javascript - 用 cdata 标签替换 script 标签

php - 标签是否可以保存在文本框列表输入中?

javascript - 基于垂直滚动使用 jquery 添加/删除类?

jquery - 验证AntiForgeryToken错误

javascript - Jquery onchange Ajax