0

Console isn't displaying the correct "people".

My function is as follows:

(function() {
  var people, length = 10;
  for (people = 0; people < this.length; people++) {
    setTimeout(function() {
      console.log(people);
    }, 1000);
  }
})();
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
Dave
  • 691
  • 2
  • 11
  • 25

2 Answers2

2

In your code this.length is not the local variable length in your function.

this is just the global object window, so this.length is just window.length.

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {        
        setTimeout((function(people){ 
           return function() { 
              console.log(people); 
           };
        })(people), 1000);
    }
})();
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

you mean like:

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {
        (function(index) {
            setTimeout(function() { console.log(index); }, 1000);
        })(people);
    }
})();
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162