延迟http请求的for循环 [英] delay in a for loop for http request

查看:40
本文介绍了延迟http请求的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用JS和Node.js.我正在尝试使用Node.js和一些模块(例如 request cheerio )构建一个简单的刮板作为第一个项目.我想在数组中包含的每个域的每个http请求之间添加5秒的延迟.你能解释一下怎么做吗?

I am just getting started with JS and Node.js. I am trying to build a simple scraper as first project, using Node.js and some modules such as request and cheerio. I would like to add a 5 secs delay between each http request for each domain contained into the array. Can you explain me how to do it?

这是我的代码:

var request = require('request');

var arr = [ "http://allrecipes.com/", "http://www.gossip.fr/" ];

for(var i=0; i < arr.length; i++) {
    request(arr[i], function (error, response, body){
        console.log('error:', error);
        console.log('statusCode:', response && response.statusCode);
        console.log('body:', body);
    });
}

推荐答案

使用 setTimeout :

var request = require('request');
var arr = ["http://allrecipes.com/", "http://www.gossip.fr/" ];

for (var i = 0; i < arr.length; i++) {
    setTimeout(request, 5000 * i, arr[i], function (error, response, body){
        console.log('error:', error);
        console.log('statusCode:', response && response.statusCode);
        console.log('body:', body);
    });
}

您基本上会进行循环,并说应该以等于 5000 * i 的延迟(等于5000ms乘以 i ,因此每次循环迭代将增加5秒.然后提供将传递给函数的所有参数.

You basically make the loop and say that the request method should be called with a delay equal to 5000 * i, which is 5000ms multiplied by i, so it will increase with 5 seconds for each loop iteration. Then you provide all the arguments that will be passed to the function.

这篇关于延迟http请求的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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