0
(function timer() {
  for (var i = 0; i <= 5; i++) {
    (function () {
      setTimeout(function clog() {
        console.log(i);
      }, i * 1000);
    })();
  }
})();

This is the output-

6
6
6
6
6
6

how is the IIFs getting loaded on the stack? are all of them pushed and then processed and popped one by one to get the i = 6? And the output does wait for 1 sec while printing 6.

Saheel Sapovadia
  • 2,755
  • 3
  • 11
  • 22
  • 3
    Haven't you used your debugger to see for yourself? – Dai Nov 22 '22 at 02:13
  • 2
    `setTimeout()` callbacks are not on the stack. They're in a queue managed by the runtime. Other than the callback when the timer fires, the stack is essentially empty. – Pointy Nov 22 '22 at 02:14
  • 1
    The explanation of this behavior is very well covered at [JavaScript closure inside loops – simple practical example](/q/750486/4642212). – Sebastian Simon Nov 22 '22 at 02:44

1 Answers1

3

var will make it a global variable,in order to make it work as you expected,need to change

var i = 0; i <= 5; i++

to

let i = 0; i <= 5; i++

(function timer() {
  for (let i = 0; i <= 5; i++) {
    (function () {
      setTimeout(function clog() {
        console.log(i);
      }, i * 1000);
    })();
  }
})();
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • 2
    To elaborate on this a bit: `var i` gets scoped to the function (timer), not the loop. So each timeout callback is using the same `i`, and by the time your first console.log runs the loop is finished and i's value is 6 – ray Nov 22 '22 at 02:32