-3

Loop works fine without setTimeout but not with it. What caused it? Thanks you in advance

const sentence = "The quick brown fox jumps over the lazy dog.";

for (var i = 0; i < sentence.length; i++) {
    setTimeout(() => {
        console.log(
            `The character at index ${i} is ${sentence.charAt(i)}`
        );
    }, (i + 1) * 100);
}
IamJomm
  • 1
  • 2

2 Answers2

1

Use let instead of var:

const sentence = "The quick brown fox jumps over the lazy dog.";

for (let i = 0; i < sentence.length; i++) {
    setTimeout(() => {
        console.log(
            `The character at index ${i} is ${sentence.charAt(i)}`
        );
    }, (i + 1) * 100);
}

Another way could utilize the fact that setTimeout can pass arguments to the function that will be called:

const sentence = "The quick brown fox jumps over the lazy dog.";

for (var i = 0; i < sentence.length; i++) {
    setTimeout((x) => {
        console.log(
            `The character at index ${x} is ${sentence.charAt(x)}`
        );
    }, (i + 1) * 100, i);
}
Marco
  • 7,007
  • 2
  • 19
  • 49
0

Because before you started printing, the variable i has reached to value 44 already. That's why it printed 44. and at index 44, there is no char, that's why no char showed.

Ae Leung
  • 300
  • 1
  • 12