Possible Duplicate:
Javascript closure inside loops - simple practical example
I have a simple question. I am working with the HTML5 canvas element and I have a loop that draws a series of boxes on the canvas. This code works fine:
for (var i = 0; i < this.boxes.length; i++) {
this.drawBox(canvas, this.boxes[i]);
}
Now I wanted to add a slight delay to the box drawing loop so I changed the loop to this:
for (var i = 0; i < this.boxes.length; i++) {
var me = this;
var xcanvas = canvas;
var box = this.boxes[i];
var func = function () {
me.drawBox(xcanvas, box);
};
window.setTimeout(func, i * 50);
}
The second loop only draws one box out of the this.boxes array (array can contain anywhere from 1 - 16 boxes). All other code is identical in the source. How can this be?
** Verbose variable declarations were used to troubleshoot references **
Any help would be GREATLY appreciated.