Raxkin Raxkin - 14 days ago 7
Javascript Question

Index of "for" inside "setInterval"

I have an object and i put it in a Array, and the i iterate the array with

for
and for each object in the array i put a set interval for calling a method of the object with a parameter, but i cant.
This is my "Class".

function ClassTest() {
this.test = function(word) {
console.log(word);
}
}


The i create the object and put it on a Array:

var array = [];
var objectTest = new ClassTest();


array.push(objectTest);


And when i set the Intervals:

for(var i = 0; i < array.length; i++) {
array[i].loop = setInterval(function() {
array[i].test("hello")
}, 1000);
}


The problem is that the var
i
in the setInterval function dosent exist, i can create a var
index
and the it exist but i dont understand why
index
exist and the var
i
not.:

for(var i = 0; i < array.length; i++) {
var index = i;
array[i].loop = setInterval(function() {
array[index].test("hello")
}, 1000);
}


I get this error when i dont use the
index
var:

Uncaught TypeError: Cannot read property 'test' of undefined

Answer

Because your for loop executes immediately. By the time your setInterval() executes for the first time, your for loop will have long since finished and your i will be outside of the range of your array.

Example

In this example, our array has a length of 3. When our for loop finishes, our i variable will be equal to 3. The number 3 will be displayed three times in our JavaScript console if we log i within the setTimeout:

var array = [1, 2, 3];

for (var i = 0; i < array.length; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

Comments