In JavaScript, a for loop does not open a new scope for variables. Your obj variable has at least function scope (if your code is in a function, or otherwise global scope). That is, each iteration through the for loop in fact changes the value of the single obj variable in the function. When you leave the for loop, you end up with a lot of timers, but they all call update on the same object.
To prevent that you need to extract your loop body into another function so as to create a new scope for each iteration. Alongside with some other recommendations, it could look like this:
var i, n;
for (i = 0, n = objects.length; i < n; i++) {
createIntervalToCallUpdate(objects[i]);
}
And your function:
function createIntervalToCallUpdate(objectToUpdate) {
var repeater = setInterval(function () { objectToUpdate.update(); }, 1000);
}
To get more understanding on this, read about a concept called "hoisting", for example in this article about scoping and hoisting. Hoisting is also a reason why many recommend to declare all your variables at the top of the function. If you declared obj at the top of your function (which implies, outside the for loop), you wouldn't be trapped into believing that the variable could be redefined for each iteration.
Update: Philipp's suggestion is great as it makes the code simpler and easier to read (given that your browser supports array.forEach which is rather new). It basically does exactly what the code above does, except it already does the task of the first snippet for you.
objects.lengthbefore the loop, as it is recalculated on each iteration if called during the loop's creation.objects.lengthbefore the loop, as it might be evaluated on each iteration depending on the JavaScript interpreter"Thread.Sleep(1000)every time an object length is accessed but none do. Cachingarray.lengthis not faster in any JavaScript interperter from the last few years and it just adds clutter. On the other hand, caching the lengths of DOMNodeLists is important (this is a rather common misconception) asNodeLists are live - this means that if you get elements withgetElementsByTagNameand append new elements with that tag name in the loop you get an infinite loop. Fun