0

I have a function that handles sending requests when a button is clicked, however the requests just get "blasted" and I want them to be a bit spaced out in time, say 500ms apart.

Here is what I have tried:

async function SendRequests() {
  requestsToSend.forEach(async (request) => { 
    request.Send();
    
    await new Promise((resolve) => setTimeout(resolve, 500));
  });
}

But it doesn't work the requests still get blasted. I have seen this approach in another answer to a similar question, and I have also used it in my own code on the NodeJS side and it works there, but I can't get it to work on the React side.

I have also tried this:

function SendRequests() {
  requestsToSend.forEach((request) => { 
    setTimeout(()=> { request.Send(); }, 500)
  });
}

And it kinda works, but they still get blasted. What I am guessing is happening here is that, all of the setTimeouts get queued and they just count out at the same time.

2 Answers 2

1

You can schedule the timeouts based on the request index:

function SendRequests() {
  requestsToSend.forEach((request, index) => { 
    setTimeout(()=> { request.Send(); }, 500 * (index + 1))
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

The first question I would have i why would you not want to send all requests at the same time? If you do this to make sure you don't have any race conditions i'm not sure if this is the correct way of handling it.

However, you could solve this problem by settings an interval instead of a timeout.

let count = 0;
setInterval(() => { list[count].send(); count++ }, 500);

3 Comments

Because the requests are being sent to a device and I am not sure if it can handle a blast of requests, so I prefer to play it safe, as waiting 2 seconds is not a problem.
Also wasnt setInterval for executing a piece of code every X seconds? I don't want that.
Ahh I forgot about that. You would have to manually check when to cancel the interval. I think thedudes example would work better for your usecase

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.