I’m trying to run multiple timers given a variable list of items. The code looks something like this:
var list = Array(...);
for(var x in list){
setInterval(function(){
list[x] += 10;
console.log(x + "=>" + list[x] + "\n");
}, 5 * 1000);
}
The problem with the above code is that the only value being updated is the item at the end of the list, multiplied by the number of items in the list.
Can anyone offer a solution and some explanation so I know why it’s behaving this way?
So, a few things:
setInterval()maintains a reference toxrather than the snapshot value ofxas it existed during each particular iteration. So, asxis changed in the loop, it’s updated within each of the callback functions as well.for...inis used to enumerate object properties and can behave unexpectedly when used on arrays.setTimeout()rather thansetInterval().You can pass arguments to your callback function by supplying additional arguments to
setTimout():Numbers will be passed by value rather than reference. Here’s an example: