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:
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.
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.
After 30 sec or specified time, it should again start sending 100 more requests, then again stop and again send, etc.
How do I do this?
CodePudding user response:
You need setTimeout(setInterval) structure for that. In the outer setTimeout you set initial delay which is 600ms, and in inner setInterval you set 30sec delay.
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.
CodePudding user response:
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
}
})