0
const screenDiv = document.getElementById('screen');

function outputKorv() {
    const paragraph = document.createElement('p');
    screenDiv.appendChild(paragraph);
    const korv = new Array('k', 'o', 'r', 'v');
    let index = 0;
  
    while (index < korv.length) {
    const letter = document.createTextNode(korv[index]);
    setTimeout(console.log(letter), 1000);
    index++;
    }
}

outputKorv();

When I run the script the letters are written to the console immidiately, and not as I expected with a 1 second gap between them. I've also tried to put the increment in the timeout, but I can't get that to work either. I've tried: setTimeout(index++, 1000), setTimeout('index++', 1000), and setTimeout(() => index++, 1000), but neither works. I've also tried a for loop, and do ... while, but I'm getting the same result with those too. The idea is to output the word 'korv' to an HTML-page one letter at a time. Can someone explain what I'm doing wrong?

  • You need to pass a function in timeout and not a statement, try with `()=>console.log(letter)` – Shub Jul 24 '22 at 09:41
  • `setTimeout(console.log, 1000, letter);` is also valid – Jaromanda X Jul 24 '22 at 09:46
  • also, setTimeout's don't wait for each other ... so when you do it right, all timeouts will trigger at about the same time – Jaromanda X Jul 24 '22 at 09:49
  • The idea is to make the loop pause after each character. I've tried to pass a function (`() => console.log(letter)`) as well but it's still outputting all at once. – crashdelta Jul 24 '22 at 10:09

2 Answers2

0

The solution seems to be a recursive function instead of a loop.

  • This works but is more complicated to reason about and maintain. I recommend an asynchronous loop instead. – CherryDT Jul 24 '22 at 10:50
0

My recommendation is: Make the function async, define a delay function as const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) and then simply call await delay(1000) at the point where you want to wait. This will greatly simplify the logic.

Here is the updated code. I took the liberty to also replace the verbose while loop with a for loop and get rid of the deprecated new Array syntax.

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const screenDiv = document.getElementById('screen');

async function outputKorv() {
    const paragraph = document.createElement('p');
    screenDiv.appendChild(paragraph);
    const korv = ['k', 'o', 'r', 'v'];
  
    for (let index = 0; index < korv.length; index++) {
      const letter = document.createTextNode(korv[index]);
      console.log(letter)
      await delay(1000);
    }
}

outputKorv();
CherryDT
  • 25,571
  • 5
  • 49
  • 74