0
let text = "Lorem ipsum dolor sit amet";

for(let i = 0; i < text.length; i++){
    setTimeout(console.log(text.charAt(i)), 2000);
}

I need this text to be printed one character at once with 2 seconds delay but it is not stoping. why using setTimeout has no effect it just goes on without any delays.

  • 3
    Change it to `setTimeout(() => console.log(text.charAt(i)), 2000)` – Dominik Matis Feb 06 '21 at 18:55
  • 1
    Because you must pass a function to `setTimeout`. It's not a `sleep` call, it's a "schedule for later and continue immediately" – Bergi Feb 06 '21 at 18:59
  • thank you very much for response but why does it needs to have this can you give me a explanation or any source @DominikMatis –  Feb 06 '21 at 18:59
  • Because `console.log(..)` just returns value `undefined`, `setTimeout` needs a function – Dominik Matis Feb 06 '21 at 19:01
  • `()` calls a function immediately; you're just passing the return value of that function call to `setTimeout`. – deceze Feb 06 '21 at 19:01

0 Answers0