0

I am running

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }(i), 4000);
}

Above code not waiting for 4 sec, it instantly prints 0, 1, 2.

Can somebody explain the reason for this output?

Thanks!

adiga
  • 31,610
  • 8
  • 53
  • 74
Pranjal
  • 443
  • 1
  • 6
  • 19
  • 2
    Yes, you're immediately executing your callback. If anything, your IIFE needs to *return another function*. – deceze May 14 '19 at 13:16
  • 1
    In more words: `function () { console.log(i); }` is a function which, when called, will log the value of `i`. And you're immediately calling this function. If anything, you want this function to be a function which, when called, *returns another function which, when called, logs the value of `i`.* See the duplicate for many examples of that. – deceze May 14 '19 at 13:21

0 Answers0