Skip to content Skip to sidebar Skip to footer

RequestAnimationFrame Position In Code

Can someone please share where you should have the RequestAnimationFrame call in the animation loop. Should it be at the beginning of the loop or the end of the loop? I've seen it

Solution 1:

I've seen most coders put requestAnimationFrame at the bottom of the loop...

But I'm not sure that's necessary. Let's say you start a first loop. Then, in that first loop the you immediately request a second loop. The first loop will always fully execute before the second loop is even attempted.

That's because requestAnimationFrame queues multiple incomplete frame loops for you so if the current loop runs long it will just delay the next loop until the current loop finishes. You won't have dropped frame loops when using rAF.

Demo showing how requestAnimationFrame queues loops

This demo runs 10 loops with requestAnimationFrame put at the top of the loop function. The code in the loop intentionally delays 1 second -- much longer than a typical rAF cycle of 1/60th second. Even so, rAF properly executes all 10 loops even though each loop takes much longer than the usual 17ms per rAF loop.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var loopCount=0;

requestAnimationFrame(loop);

function loop(time){
    loopCount++;
    if(loopCount<10){ requestAnimationFrame(loop); }    
    var t1=performance.now()+1000;
    while(performance.now()<t1){}
    ctx.fillText('Loop count: '+loopCount+', time: '+time,20,loopCount*15);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<h4>rAF at top of loop still runs all 10 frames even<br>if the code in the loop takes extra long to complete</h4>
<canvas id="canvas" width=300 height=300></canvas>

Post a Comment for "RequestAnimationFrame Position In Code"