在的setTimeout循环的Node.js [英] setTimeout in Node.js loop

查看:213
本文介绍了在的setTimeout循环的Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,如何的setTimeout 的作品。我想在一个循环中有一个的setTimeout ,使循环迭代,比如,1秒分开。
每次循环发出一个HTTP请求,它似乎像另一端的服务器无法处理在这么短的时间跨度,很多的请求。

I'm a bit confused as to how setTimeout works. I'm trying to have a setTimeout in a loop, so that the loop iterations are, say, 1s apart. Each loop iteration makes an HTTP request and it seems like the server on the other end can't handle that many requests in such a short time span.

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

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

为什么这不是工作,我怎么能做到这一点?

Why does this not work and how can I achieve this?

感谢您

推荐答案

您需要像这样

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

另请参阅这个小提琴

警报点(计数); ,你可以做你的服务器调用。
需要注意的是柜台工作(倒计时)相反。我与一些更新
评论哪里做你的事。

At the point of the alert(count); you can do your call to the server. Note that the counter works opposite (counting down). I updated with some comments where to do your thing.

这篇关于在的setTimeout循环的Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆