如何使用for循环超时ajax请求



如何使用带超时的for循环每5秒请求一次ajax

function req() {
$.ajax({ .......
})
}
for (var i = 4000; i <= 6000; i++) {
setTimeout(function() {
req(i)
}, i * 5000);
}

不要循环Ajax。如果服务器过载,您将堆叠将取消彼此的请求

取而代之的是

function req() {
$.ajax({ .......
success: function() {
setTimeout(req,5000)
}
})
}

如果你想以3个不同的间隔发送,你可以这样做

const timeouts = [4000,5000,6000];
let cnt = 0;
function req() {
$.ajax({ .......
success: function() {
setTimeout(req,timouets[cnt]); // move this to an if to stop after 3 calls
cnt++; if (cnt>= timeouts.length) {
cnt = 0;
}
}
})
}

您可以使用在每次5s之后发送请求

time + time * (i - start)

function req(s) {
console.log("After " + s + "s");
// $.ajax({.......})
}
const start = 4000,
end = 6000,
time = 5000;
for (let i = start; i <= end; i++) {
setTimeout(function () {
req((time + time * (i - start)) / 1000); // I've passed the time to track the passed seconds
}, time + time * (i - start));
}

您可以将其视为通过for循环创建一系列经过时间的请求。

function req() {
console.log('requested');
}
for (let i = 1; i <= 10; i++) {
setTimeout(req, i * 5000)   
}

然而,使用setInterval也可以很容易地实现这样的一系列请求。

function req(){
console.log('requested');
}
const limit = 10;
let counter = 1;
let handler = setInterval(function(){

req();

counter++;

if (counter >= limit)
clearInterval(handler);

}, 5000)

最新更新