0

I have a simple array of strings example:
let arr = ["hello", "hello world", "hi js", "javascript"]
all i want to do just print every character of each word on the console after say 2sec
so i tried this

for(let i = 0; i < arr.length; i++) {
    for(let j = 0; j < arr[i].length; j++){
        setTimeout(() => {
            let char = arr[i].charAt(j);
            console.log(char);
        }, 2000)
    }
}

but somehow this prints all characters after 2 seconds
i want to print one character wait 2 seconds then print another and so on...

  • Does this answer your question? [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Ivar Mar 01 '21 at 17:38

1 Answers1

1

While you could multiply the timeout duration by the time required for the character plus the time required for prior words - I think it'd be easier to promisify it and use await:

let arr = ["hello", "hello world", "hi js", "javascript"]

const delay = () => new Promise(resolve => setTimeout(resolve, 500)); // replace with 2000
(async () => {
  for (const string of arr) {
    for (const letter of string) {
      console.log(letter);
      await delay();
    }
  }
})();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320