-1

可能重复:
如何在 JavaScript 循环中添加延迟?

我想从对象发送一些POST请求,而无需等待睡眠后的响应。在循环中,正在发送此请求。如果我不等待就发送所有请求,我的浏览器会暂时没有响应,服务器端也不允许这样做。我怎样才能在所有这些请求中加入睡眠? 这就是我正在使用的 -xmlhttpjavascriptforPOST

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);
}
4

1 回答 1

1

没有办法延迟当前脚本的执行。您将不得不使用异步请求并重组您的代码。

因此,如果您有这样的代码:

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
于 2012-10-14T10:42:59.480 回答