0

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.

Community
  • 1
  • 1
It's Me
  • 1
  • 1
  • 4
    Typical "closure in loop problem", please have a look at http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Felix Kling Jun 20 '12 at 02:28

1 Answers1

0

I do not know the exact answer to your problem, but what I did in a similar case was just to setInterval for 50 msec, then in that interval function clearInterval and setInterval again with 50 * i... Something along the lines of below:

var initialDelay = 50;
var counter = 0;
var intervalID;

intervalID = setInterval(myFunction(initialDelay), initialDelay);

myFunction(delay) {
     if (counter >= this.boxes.length) {
         clearInterval(intervalID);             
         //Clear interval and do nothing
     }
     clearInterval(intervalID);
     me.drawBox(xcanvas, box); //Do the stuff you want to do in your interval
     intervalID = setInterval(myFunction(delay * 50), initialDelay);
}

The setInterval essentially acts like a loop.

Marc
  • 561
  • 5
  • 17
  • The problem and possible solutions are provided in the post I linked to in my comment. I honestly don't see how `setTimeout` can help here. – Felix Kling Jun 20 '12 at 02:54
  • Yes, this question was exactly what Kling and others stated, a closure problem. See Kling's comment for solutions. – It's Me Jun 20 '12 at 18:59