var a=0;
setTimeout (function () { animatedDraw(context, 20+32*level[0],20*0, textArray[0]); }, timeArray[0]);
setTimeout (function () { animatedDraw(context, 20+32*level[1],20*1, textArray[1]); }, timeArray[1]);
setTimeout (function () { animatedDraw(context, 20+32*level[2],20*2, textArray[2]); }, timeArray[2]);
setTimeout (function () { animatedDraw(context, 20+32*level[3],20*3, textArray[3]); }, timeArray[3]);
setTimeout (function () { animatedDraw(context, 20+32*level[4],20*4, textArray[4]); }, timeArray[4]);
setTimeout (function () { animatedDraw(context, 20+32*level[5],20*5, textArray[5]); }, timeArray[5]);
for (a=0; a<6; a++)
setTimeout (function () { animatedDraw(context, 20+32*level[a],20*0, textArray[a]); }, timeArray[a]);
The first part of my code is the part that works. The second part does not show up. I am drawing in a canvas (HTML 5), but when I popped six alert boxes, the alert boxed showed.
Am I doing something very stupid wrong?
Thanks in advance
The reason is that the functions you’re feeding into
setTimeoutare closures, and closures have an enduring reference to the variables they close over, not a copy of their values as of when the closure was created. Consequently, all of those functions will try to use the same value ofa, the value it has after the loop is complete (e.g. 6) and so they’ll fail.The answer is to have the functions close over some other data instead that won’t change. The usual way to do that is to have a factory function that creates and returns the actual functions you want, having them close over the argument you feed into the factory function (which won’t change) rather than your loop variable. E.g.:
As you can see, now the functions being created by
makeTimerFunctionare closing overindexrather thana(and also overcontext,level, andtextArray; you’d pass those in as well if they change).More on closures: Closures are not complicated