I'm trting to do the following:
I'm running through a for loop and each time I get a new information and want to draw it on the canvas. The problem is that the canvas is being drawn just after the loop finish, and I can't see no animation. If I step in with debug, or with alert messages, it will draw to the canvas immediatly. How can I do it?
Here is my code, as you can see I've already tried with setTimeout in multiple ways but didn't worked.
for(var i=0;i<1000; i ++)
{
addLines(ga.getBestCreature()); // This method draw on the canvas
setTimeout(function() {
ga.startEvolution(1); // This method change the best creature
}, 10);
}
The drowing method:
function addLines(best) {
if(!best) {
return;
}
var global_path = best.data;
redraw(); // Clear off the canvas
var cityA;
var cityB;
for (var i = 0; i < (global_path.length - 1); i++) {
cityA = ga.cities[global_path[i]];
cityB = ga.cities[global_path[i+1]];
ctx.moveTo(cityA.x,cityA.y);
ctx.lineTo(cityB.x,cityB.y);
ctx.stroke();
}
}
Any Ideas??
Update: After was advised to use the requestAnimationFrame, I've came out with something like this. Is this the best approach? I'm updating a global variable called 'run' on click events
var run = 0;
function animate() {
if(run > 0) {
ga.startEvolution(1);
run--;
}
addLines(ga.getBestCreature());
requestAnimationFrame(animate);
}
animate();