Isquare Isquare - 1 month ago 6
Javascript Question

javascript loop with delay code fix

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();

Answer

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.

Comments