简体   繁体   English

循环和 forEach

[英]Loops and forEach

let char = [5, 3 , 1, 7]

let i = 1

char.forEach((num) => {
    i++
    setTimeout(function () {
        request({
            url: "//someUrl",
            method: "POST",
            json: {//Some Json}
        }, function (err, response, body) {
            console.log(body);
        })
    }, i * 600)
})

In the following code each of the request is executing after 600 milliseconds and I want so that:在下面的代码中,每个请求都在 600 毫秒后执行,我希望这样:

if(i % 100 === 0){
//Something to wait 30 sec before executing the same loop
}

How do I do with the code above to work?如何使用上面的代码工作?

Explanation in other words: The code given now has a loop for each item in array now I want to use each item in this array so I used forEach function now I even want a request inside it, so I added and what it does it spam sends request to that server without waiting a second, around 100 requests/sec.换句话说:现在给出的代码对数组中的每个项目都有一个循环现在我想使用这个数组中的每个项目所以我使用了 forEach function 现在我什至想要一个请求,所以我添加了它的垃圾邮件无需等待一秒钟就向该服务器发送请求,大约 100 个请求/秒。

I have set it that it waits 600 milliseconds before executed forEach loop again now I even want that after it had requested 100 times, to stop sending request for 30 sec so that it processes all the information I have sent till now.我已将其设置为在再次执行 forEach 循环之前等待 600 毫秒,现在我什至希望在它请求 100 次后停止发送请求 30 秒,以便它处理我迄今为止发送的所有信息。

After 30 sec or specified time, it should again start sending 100 more requests, then again stop and again send, etc. 30 秒或指定时间后,它应该再次开始发送 100 多个请求,然后再次停止并再次发送,等等。

How do I do this?我该怎么做呢?

You need setTimeout(setInterval) structure for that.为此,您需要 setTimeout(setInterval) 结构。 In the outer setTimeout you set initial delay which is 600ms, and in inner setInterval you set 30sec delay.在外部 setTimeout 中设置初始延迟为 600 毫秒,在内部 setInterval 中设置 30 秒延迟。

let char = [5, 3 , 1, 7];

char.forEach((num) => {
    setTimeout(
        setInterval(
            doHundredRequests();
        ), 30000),
    600);
});

But generally, using async-await would be better than using setTimeout or setInterval to fetch responses.但一般来说,使用 async-await 会比使用 setTimeout 或 setInterval 来获取响应更好。

Answer is:答案是:

let a = null

char.forEach((num) => {
    i++
    setTimeout(function () {
        request({
            url: "//someUrl",
            method: "POST",
            json: {//Some Json}
        }, function (err, response, body) {
            console.log(body);
if(a){
i = a
a = null
console.log("Waiting triggered")
}
        })
    }, i * 600)
if(i % 100 === 9){
a = i
i = 30000/600
}

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM