0

for (var i = 0; i < 3; i++) {
  const fun = () => console.log(i);
  
  setTimeout(() => {
    fun();
  }, 1000);
}

I got this output: 3 3 3. This will print 3 three times.

From MDN:

The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • I think it was asked many times in those terms already... you will surely find it here on SO. Anyway you are instantly defining 3 times a different function using the `i` variable that will hold the number `3` when those will actually be called – Diego D Feb 20 '23 at 09:38

0 Answers0