1

I have a function that fires up request multiple times, but need to add delay between each so that I don't spam the server:

async function multiReq(iterationNr){

    for (let i=0; i++; iterationNr ) {
    //send request here
    res.push(resultOfTheRequest);
    }
    return res;
};
console.log(multiReq(10));

Where should I have timeout so that I have e.g. req 1, wait 1 sec, req 2, wait 1 sec until finished and then return res array?

2 Answers2

3

One option would be to await a Promise that resolves after 1 second whenever you need to add a delay:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function multiReq(iterationNr){
  const res = [];
  for (let i=0; i < iterationNr; i++) {
    // If you don't need to wait for the response to come back yet, remove the await:
    const result = await makeRequest();
    await delay(1000);
    res.push(result);
  }
  return res;
}

Also note that for loops have the condition second, and the incrementer third, not the other way around, and that function blocks } should not have semicolons after the end.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

I found that if you are using http 1.1 and you put “Connection: close” (default is “keep-alive”) in the header of the request, then you don’t need the delay and you can fire off as many requests this way as you like.

westandy
  • 1,360
  • 2
  • 16
  • 41