我刚开始使用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 = [ "allrecipes/", "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 = ["allrecipes/", "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循环
发布评论