0

I want to make a delay of 1 second in each iteration of the loop. But when I am trying to do so, it is running all over and then waiting in the end.

What can be the possible change so that loop waits for 1 second before invoking the function.

Tried answer at Using async/await with a forEach loop but didn't work with this use case.

When you will run this code below you will see that first it invokes the function 5 times, then wait and then prints the date.

const arr = [1, 2, 3, 4, 5];

async function foo(item) {
  console.log('Function invoked at index: ', item);
}

arr.forEach(async (item) => {
  await foo(item);
  await new Promise((resolve) => setTimeout(resolve, 1000));
  console.log(new Date().toLocaleString());
});
  • 1
    You cannot do that using `forEach` because it just loops through and executes what can be executed instantly. Promises will be moved to a separate thread and once it gets resolved, they are moved back to the call stack for execution. If you want a delay here, you must use a `for ..of` like `async function myFunc () { for (const item of arr) { await foo(item); await new Promise((resolve) => setTimeout(resolve, 1000)); console.log(new Date().toLocaleString()); } }` – Vishnu Sajeev Dec 28 '21 at 11:51
  • @VishnuSajeev "*Promises will be moved to a separate thread*" - no?! Promises have nothing to do with multithreading. – Bergi Dec 28 '21 at 15:16
  • "*Tried answer at Using async/await with a forEach loop but didn't work with this use case*" - if you need further assistance, please [edit] your question to include the exact code you tried and how it didn't work. – Bergi Dec 28 '21 at 15:18

0 Answers0