Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  139] [ 3]  / answers: 1 / hits: 66631  / 13 Years ago, thu, october 13, 2011, 12:00:00

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?


More From » for-loop

 Answers
6

So, a few things:




  1. Most importantly, the callback function you've passed to setInterval() maintains a reference to x rather than the snapshot value of x as it existed during each particular iteration. So, as x is changed in the loop, it's updated within each of the callback functions as well.

  2. Additionally, for...in is used to enumerate object properties and can behave unexpectedly when used on arrays.

  3. What's more, I suspect you really want setTimeout() rather than setInterval().



You can pass arguments to your callback function by supplying additional arguments to setTimout():



var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);


Numbers will be passed by value rather than reference. Here's an example:





var list = [1,2,3,4];

for (var x = 0, ln = list.length; x < ln; x++) {
setTimeout(function(y) {
console.log(%d => %d, y, list[y] += 10);
}, x * 500, x); // we're passing x
}




[#89641] Wednesday, October 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rickjordond

Total Points: 100
Total Questions: 105
Total Answers: 90

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
rickjordond questions
;