Here is the part of the code that matters:
function drawCircle(i, color1, color2) {
var ctx = canvas.getContext("2d");
if (i % 2 == 1) {
ctx.fillStyle = color1;
}
else {
ctx.fillStyle = color2;
}
ctx.beginPath();
ctx.arc(110, 270, 10, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
for (var i = 0; i < 10; i++) {
setTimeout(drawCircle(i, color2, color5), 4000);
}
Note that this is just a snippet I wanted to try out before I use code similar to this on a larger project. This isn’t working properly, the image is only drawn once, that is, I only see the last circle that is drawn. I have googled this to death but nothing has helped me so far.
What you want to use is
setInterval.setTimeoutjust fires the event once. They have the same argument list.Also I don’t think the way you use
setTimeoutis correct. The way you’ve written it now, the function is fired before actually passing anything tosetTimeout/setInterval. So you should write:or:
and NOT:
EDIT
You don’t have any blocking routines in JavaScript. It’s a single threaded, event driven language. If you call something like
setIntervalit succeeds immediately. Only after 4 seconds or so your callback function will be invoked. However in the meantime JS will be busy doing all sort of different stuff – like for example reacting to other events generated by the user. What you want to do is to callsetTimeoutonce and then inside the callback function, just before returning invoke it again with the same function and a different set of arguments ofi. Something along these lines: