Isquare Isquare - 1 year ago 126
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)



Answer Source

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() {
    if (i < azj.length) {
  }, 3000)


For more information, check out this answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download