How to slow down the loop in JavaScript

I have a loop and I want to call the API multiple times, for example 500 times.

The API implements rate limiting. Even if there is no limit, it is unfriendly to make so many requests in a short period of time.

So I want to slow down the loop. how is it?

It turns out that after setting the sleep() function, you don't need to change it and it's very simple:

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

Then you can callawait sleep(1000)Stop for 1 second in each iteration, as shown below:

const list = [1, 2, 3, 4]
const doSomething = async () => {
  for (const item of list) {
    await sleep(1000)
    console.log('🦄')    
  }
}

doSomething()

Download mine for freeJavaScript beginner's manual


More js tutorials: