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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's exactly what I've been looking for
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.