0

for (let i = 0; i < 10; i++) {
  // debugger
  var log = function () {
    // debugger
    console.log(i)
  };
  var logWrappper = function () {
    console.log(i);
    log();
  }
  // logWrappper();
  setTimeout(logWrappper, 10)
}

I have code like above, if I invoke logWrapper directly,the console.log(i) outputs the same result(0-9) both in log and logWrapper, however if I pass it to a setTimeout and invoke it later, console.log(i) in logWrapper remains the same(0-9) while it outputs 10 times 9 in log, can anybody explain it? thank you very much.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values This will probably answer your question. – Abhay Srivastav Aug 04 '22 at 08:01
  • 1
    Because it just calls `log`, and there's only one `log` at call time, the last one that has been defined. – deceze Aug 04 '22 at 08:04
  • 2
    `i` uses `let` (scoped to the loop) so you get new `i` each loop. `log` uses `var` (scoped to the function) so `log` function gets overwritten each loop and the last `log` uses the `i` from the last loop. – Quentin Aug 04 '22 at 08:06

0 Answers0