0

I have an forEach loop that make an async call to an API:

array.forEach(async (item) => {
  await callAnApi(item)
})

I want to make this loop wait 1 second between the items - because the API is getting sattured.

We need something like this:

array.forEach((item) => {
  setTimeout(async () => {
     await callAnApi(item)
  },1000)
})

That way it doesn't work because the whole loop runs in the "same time" so every call will be fired "in the same time" after 1 second.

I already have searched for dozens of answers but none of them have solve this simple problem.

4 Answers 4

1

You could increment the timeout delay:

array.forEach((item, count) => {
  setTimeout(() => callAnApi(item), count * 1000);
});

That sets up timers at 1 second intervals instead of all being at the same time.

1

This should help you

const array = [1, 2, 3]

const wait = (ms) =>
  new Promise((resolve, reject) =>
    setTimeout(() => {
      resolve()
    }, ms)
  )

const run = async () => {
  for (const a of array) {
    console.log(a)
    await wait(1000)
  }
}

run()

1

Something like this:

await array.reduce(
  (acc, item) => acc
    .then(() => callAnApi(item))
    .then(() => new Promise(resolve => setTimeout(resolve, 1000))),
  Promise.resolve()
);

Note that this code will wait for an extra 1000ms after the final call is done, so you may want to improve on that.

0

Don't know the exact requirements, but since you know the length of the array, why not simply adjust the delay for setTimeout by the current index?

[1,2,3].forEach((element, index) => setTimeout(() => yourApiCall(element), index * 1000))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.