var flag = true;
function changeColor (element) {
if(flag==true){
document.getElementById(NAME+element).style.background="red";
flag=false;
}
else if (flag==false){
document.getElementById(NAME+element).style.background="white";
flag = true;
}
}
var temp;
for(var i=0;i<elements_array.length;i++)
{
alert("VAL="+elements_array[i]);
temp = elements_array[i];
setInterval(function() { changeColor(temp); } ,300);
}
The above code works only for the last value. I’m trying to change color a particular cell which i get from integer array(elements_array).
In the alert i get the array values correctly ,say 2,5,8. But only 8th (last) one is changing the color.
But if i hard code the values as the following all the cells change color.
setInterval(function() { changeColor(2); } ,300);
setInterval(function() { changeColor(5); } ,300);
setInterval(function() { changeColor(8); } ,300);
Any ideas on why the loop is not working? Thank you
Actually your code references the same
tempvariable in all iterations of theforloop. That way all instances of thesetIntervalfunctions get passed the same reference and thus the same value (at the time of execution of the function passed tosetInterval).To solve this, use something like the following function to create the callback for
setIntervaland change your
setIntervalcall accordingly toThe additional function call actually makes a copy of your
tempvalue and thereby passes a different value to each call ofchangeColor.