没有办法延迟当前脚本的执行。您将不得不使用异步请求并重组您的代码。
因此,如果您有这样的代码:
function postData() {
for (var i = 0; i < users.length; i++) {
var http = new XMLHttpRequest();
//set args here, which is based elements of array users
http.open('POST', '/user/home/index.php', true);
//Set all headers here then send the request
http.send(args);
//access request result
if (http.status == 200) {
console.log(http.responseText);
} else {
console.log('request error');
}
}
}
像这样改变它:
var userIndex = 0;
function postData() {
if (userIndex >= users.length) {
//no more users to process
return;
}
var http = new XMLHttpRequest();
//set args here, which is based elements of array users
http.open('POST', '/user/home/index.php', true);
//set request handler
http.onreadystatechange = function() {
if (http.readyState != 4) return;
if (http.status == 200) {
console.log(http.responseText);
} else {
console.log('request error');
}
//process next user index
userIndex++;
window.setTimeout(function() {
postData(); //do it again
}, 5000); //5 seconds delay
};
//Set all headers here then send the request
http.send(args);
}
postData(); //start the request chain