0

I am looking for a simple way which will allow me to use a sample like this. I have an Array and i am looping over the array but want to wait for 2 sec before i go to the next element. For some reason i cant get it to work. It waits but then goes thru all elements at once

var obj = [1,2,3,4,5,6,7,8,9]
  const delay = (amount = number) => {
    return new Promise((resolve) => {
      setTimeout(resolve, amount);
    });
  }
  async function loop() {
  obj.forEach(async(element)=>{

      console.log("hello " + element);
      await delay(3000);
    })
  }

  loop()
MisterniceGuy
  • 1,646
  • 2
  • 18
  • 41
  • 1
    Use a for…of loop, not Array#forEach. (`forEach(async …` is always wrong. Async functions return promises and `forEach` discards them.) – Ry- Jun 07 '19 at 21:32

1 Answers1

-2
let index = 0;
const timer = setInterval(() => {
    if (index === arr.length) {
        clearInterval(timer);
        return;
    }
    console.log(arr[index++]);
}, 3000);

https://jsfiddle.net/5euxf0sj/