0

Just trying to console log the correct index printed on each iteration not to sure why its not working.

(function() {
  var index,
    length = 10;
  for (index = 0; index < this.length; index++) {
    setTimeout(function() {
      console.log(index);
    }, 100);
  }
})();
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 1
    Two issues: 1. You start all `setTimeout()` at the same time. 2. `index` is not bound to the actual timeout you called at that point. Thus you will get outputed `length` all the time because the loop finishes before the timeout happens. – Lain Feb 18 '20 at 10:03
  • 1
    Also, `this.length` returns undefined. I suppose you mean `index < length`? – Terry Feb 18 '20 at 10:04
  • Use `for (let index = 0; index < length; index++)` – Terry Feb 18 '20 at 10:07

0 Answers0