1

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);
}
Community
  • 1
  • 1
Dave
  • 3,812
  • 5
  • 31
  • 39
  • 2
    Duplicate. There is *only one* variable called `lookup`. Please search on SO. –  Sep 13 '11 at 09:15
  • Usually I find things on SO pretty easily, sorry for the duplicate, but for anyone interested the solution I used was [How do I pass the value (not the reference) of a JS variable to a function?](http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function) as suggested in the links at the top of the page. – Dave Sep 13 '11 at 09:30

0 Answers0