Search code examples
javascripthtmlsettimeout

settimeout inside of double for loops


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...


Solution

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