Possible Duplicate:
Javascript closure inside loops - simple practical example
How do I pass the value (not the reference) of a JS variable to a function?
Why always the last reference to the object is used in loop?
I have an array of ids which I loop over and want to use in a function called by setTimeout, however when "func" below is executed it only seems to see the last id stored in the array. I have been trying to uses closures to fix the issue but have had no success.
// loop over array an call setTimeout for loading an image
for (var i = 0; i < idlist.length; i++) {
// variable i want use in function
var lookup = idlist[i];
var func = function() {
alert(lookup); // this is always the last value in the "idlist" array
};
setTimeout(func, 500);
}