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

When you run it: 0 1 2 3 4 5 6 7 8 9 But I cannot understand how it is working like we are multiplying i with 100??

Virus
  • 9
  • 1
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – VLAZ Aug 04 '20 at 08:59
  • `100 * i` is the *timeout` after which a message would show up. – VLAZ Aug 04 '20 at 09:00

4 Answers4

1

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

so for the first loop, you have a delay of i*100=0, then the delay became 100 then 200 and so on, so the code logs i every time, but with different delays.

maha
  • 643
  • 5
  • 20
0

i is going from 0 to 9, and in each iteration, it sets a timeout to i times 100.

That is, you end up with ten timeouts set for 0ms (0 * 100), 100ms (1 * 100), 200ms (2 * 100), and so on until 900ms (9 * 100).

i | i * 100 | delay
--+---------+------
0 | 0 * 100 |   0ms
1 | 1 * 100 | 100ms
2 | 2 * 100 | 200ms
3 | 3 * 100 | 300ms
4 | 4 * 100 | 400ms
5 | 5 * 100 | 500ms
6 | 6 * 100 | 600ms
7 | 7 * 100 | 700ms
8 | 8 * 100 | 800ms
9 | 9 * 100 | 900ms
FZs
  • 16,581
  • 13
  • 41
  • 50
0

The For loop is calling the setTimeout() function total 10 times

So if simplified it can be written as follows...

setTimeout(function() { console.log(0); }, 0); # when i=0

setTimeout(function() { console.log(1); }, 100); # when i=1

setTimeout(function() { console.log(2); }, 200); # when i=2

setTimeout(function() { console.log(3); }, 300); # when i=3

and so on...

So whats happening is for each number in range of 0 to 9, setTimeout function sets the console.log() method for every interval of 100 ms. Try replacing that 100 to 1000 and you will see that the numbers are printed in a one second delay.

If you remove the i multiplied with 100 and just keep a specific value (like only 100) it will seem like all the numbers are printed at the same time after that value of interval.

Abhijit
  • 13
  • 1
  • 4
0

Thanks for Help guys I am a newbie so I was not understanding it right

settimeout(function, parameter)

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

when we are executing it the value of i doesn't change after multiplying by hundred but just gives a 100ms delay in the output and every it increases by 100ms. And at the end the delay is 900ms.

Virus
  • 9
  • 1