How to render HTML5 canvas within a loop
<p>I'm trting to do the following:</p>

<p>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?</p>

<p>Here is my code, as you can see I've already tried with setTimeout in multiple ways but didn't worked.</p>

<pre><code>for(var i=0;i&lt;1000; i ++)
    {
        addLines(ga.getBestCreature());   // This method draw on the canvas 

        setTimeout(function() {
        ga.startEvolution(1);       // This method change the best creature
        }, 10);   
    }
</code></pre>

<p>The drowing method:</p>

<pre><code>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 &lt; (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();
    }
}
</code></pre>

<p>Any Ideas??</p>

<p>Update: After was advised to use the requestAnimationFrame, I've came out with something like this. Is this the best approuch?
I'm updating a global variable called 'run' on click events</p>

<pre><code>var run = 0;
function animate() {

    if(run &gt; 0) {
        ga.startEvolution(1);
        run--;
    }

addLines(ga.getBestCreature());
    requestAnimationFrame(animate);
}

animate();
</code></pre>