-1

how to fix this code as per

How do I add a delay in a JavaScript loop?.

it still gets executed without delay .

const spkz = responsiveVoice.speak;
let azj = ['hi', 'hello', 'how are ya'];
var i = 1; //  set your counter to 1

function myLoop() { //  create a loop function

  azj.forEach((item, index) => {
    setTimeout(() => { //  call a 3s setTimeout when the loop is called
      alert(item); //  your code here
      i++; //  increment the counter
      if (i < index) { //  if the counter < 10, call the loop function
        myLoop(); //  ..  again which will trigger another 
      } //  ..  setTimeout()
    }, 10000)
  })

}

myLoop();
Community
  • 1
  • 1
Isquare
  • 23
  • 3

2 Answers2

1

You can't "pause" javascript like that. a setTimout is asynchronous, meaning it will not block synchronous code from running, so when you run any kind of "for" loop, it will call all the setTimeouts at once.

You can make a manual loop like this and delay it with recursion:

let azj = ['hi', 'hello', 'how are ya'];
var i = 0;

function myLoop() {
  setTimeout(function() {
    console.log(azj[i])
    i++
    
    if (i < azj.length) {
      myLoop()
    }
  }, 3000)
}

myLoop();

For more information, check out this answer.

Community
  • 1
  • 1
Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91
-1

You don't have to use forEach inside the loop function. Instead, you can access the array items using azj[i]

Chris Lam
  • 3,526
  • 13
  • 10