2

this example is given in official documentation of typescript but I cant understand it.

for (var i = 0; i < 10; i++) {
    setTimeout(function() { console.log(i); }, 100 * i);
}

ouptput of this snippet is:

10
10
10
10
10
10
10
10
10
10
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Related to/duplicate of: https://stackoverflow.com/q/750486/1063392 – Nathan Friend Mar 06 '18 at 16:50
  • Simplest fix is `var` -> `let`, assuming browser properly supports ES6 lexical scope – Patrick Roberts Mar 06 '18 at 16:55
  • but I cant understand if the value of i is increased to 10 in 1st output after that why its repeating 10 times. – Navneet Dabral Mar 06 '18 at 17:01
  • 1. The loop creates 10 functions to be executed with increasing delay. Fi will be executed after i * 100 ms and will log value i. So at the end we have 10 functions to be executed after 0, 100, ... 900ms. 2. Each function will print value i, but because the for loop was executed earlier the value of i is equal to 10 – Wilhelm Olejnik Mar 06 '18 at 18:03

0 Answers0