延迟http请求的for循环

编程入门 行业动态 更新时间:2024-10-28 15:28:58
本文介绍了延迟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 = [ "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循环

本文发布于:2023-10-11 17:55:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!