我想发送 50 个 AJAX 请求,每 5 个请求延迟 10 秒,然后继续,直到前一个请求成功发送后才发送下一个请求。 我还想在完成所需数量的请求后创建警报。
这是我的代码
var requestCount = 50; // Replace X with the number of requests you want to make
var requestDelay = 5; // Delay in seconds between every 10th request
var requestCounter = 0;
function makeRequest() {
$.ajax({
url: "request.php?action=manualGroupMembers",
success: function(response) {
// Handle response here
},
error: function(error) {
// Handle error here
}
});
requestCounter++;
// Wait for 10 seconds after every 10th request
if (requestCounter % 10 === 0) {
setTimeout(makeRequest, requestDelay * 1000);
} else {
makeRequest();
}
}
makeRequest();
此代码当前发送 5 个请求,延迟 10 秒,但我只希望它发送 50 个请求。此外,它同时发送所有请求,这会导致问题。我希望代码等到上一个请求成功发送后再发送下一个请求..
我建议切换到 async/await 语法,这将使代码更容易理解,然后只需在 Y 次请求后休眠 X 秒即可:)
const requestCount = 50; // Replace X with the number of requests you want to make
const delayAfterNumberOfRequest = 10; // Delay after this number of requests
const requestDelay = 10; // Delay in seconds between every Xth request
const responses = [];
const sleep = ms => new Promise(res => setTimeout(res, ms));
async function makeRequests() {
for (let i = 0; i < requestCount; i++) {
let response = await $.ajax('request.php?action=manualGroupMembers')
.catch(e => /* handle error */ true);
responses.push(response);
if (i > 0 && i % delayAfterNumberOfRequest === 0) {
await sleep(requestDelay * 1000);
}
}
}
async function test() {
await makeRequests();
console.log(responses);
}
test();