1

I have the following loop:

        for (let z = 0; z < searchArray.length; z++) {


              searchFMG(searchArray[z])
        }

Where searchFMG makes an api call (with axios) and processes the result.

The problem is that the api I need to connect to has a rate limit that I can make requests. So I tried changing it to:

setTimeout(searchFMG(searchArray[z], 1000)

which doesn't make calls for each value of z.

What is a way for me to slow down the loop or some way make these call one second apart?

Thank you

Jonathan Zier
  • 150
  • 2
  • 14

1 Answers1

2

If you want to make your connections one second apart try something like this. Make an async sleep function to mimic "waiting." Wait 1s after each request before moving to the next item in the array. This solution does involve wrapping your code inside of an async function, if not already, however.

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function performSearch(){
    for (let z = 0; z < searchArray.length; z++) {
        await searchFMG(searchArray[z]);
        await sleep(1000);
    }
}
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34