我对setTimeout的工作方式有些困惑。我正在尝试在循环中添加一个setTimeout,以使循环迭代之间相隔1秒。
每次循环迭代都会发出一个HTTP请求,似乎另一端的服务器无法在这么短的时间内处理那么多请求。

for (var i = 1; i<=2000 && ok; i++) {
    var options = {
        host:'www.host.com',
        path:'/path/'+i
    };

    setTimeout(makeRequest(options, i), 1000);
};

为什么这不起作用,我如何实现呢?

谢谢

最佳答案

你需要这样的东西

var counter = 5;

function makeRequst(options, i) {
    // do your request here
}

function myFunction() {
    alert(counter);

    // create options object here
    //var options = {
    //    host:'www.host.com',
    //    path:'/path/'+counter
    //};
    //makeRequest(options, counter);

    counter--;
    if (counter > 0) {
        setTimeout(myFunction, 1000);
    }
}

另请参阅this fiddle

alert(count);处,您可以调用服务器。
请注意,计数器的工作方向相反(倒数)。我更新了一些
评论在哪里做你的事情。

07-24 19:08
查看更多