Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add delay between each item in an array when looping over array

I have an async function that gets called that loops over an array an calls a function for each item.

In this example, the function is hitting an API endpoint and I need to wait for one item to finish before moving onto the next.

However, what currently happens is that each function gets called at roughly the same time, which is causing issues in the api response. So i need to wait 1 second between each request.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I currently have

const delayedLoop = async () => {
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const myAsyncFunc = async (i) => {
    console.log(`item ${i}`);
    await delay(0);
    return true;
  };

  const arr = ['one', 'two', 'three'];

  const promises = arr.map(
    (_, i) =>
      new Promise((resolve) =>
        setTimeout(async () => {
          await myAsyncFunc(i);
          resolve(true);
        }, 1000),
      ),
  );
  return Promise.all(promises);
}

const myFunc = async () => {
  console.log('START');
  await delayedLoop();
  console.log('FINISH');
}

myFunc();

What happens is;

  • LogsSTART
  • waits 1 second
  • Logs all item ${i} together (without delay in between)
  • Immediately logs FINISH

What I want to happen is

  • LogsSTART
  • waits 1 second
  • Logs item 1
  • waits 1 second
  • Logs item 2
  • waits 1 second
  • Logs item 3
  • Immediately logs FINISH

See JSFiddle to see it in action

>Solution :

You can do, it like this, using a simple for-loop:

const delayedLoop = async () => {
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const myAsyncFunc = async (i) => {
    console.log(`item ${i}`);
    return true;
  };

  const arr = ['one', 'two', 'three'];
  for(let i=0; i < arr.length; i++) {
     await myAsyncFunc(i);
     await delay(1000);
  }
}

const myFunc = async () => {
  console.log('START');
  await delayedLoop();
  console.log('FINISH');
}

myFunc();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading