RequestAnimationFrame position in code
Asked Answered
Y

1

1

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 written about many times with it at the beginning of the loop but wouldn't it be better to be at the bottom of the loop so it won't be called while it might still be processing? Or does the RequestAnimationFrame have a check to see if it is already running and not run it if it is running already? Or does it not matter at all? I've tried moving it around and haven't noticed any changes in my code.

Eg Top:

function gameLoop() {
   RequestAnimationFrame(gameLoop);

   renderFrameHere();
}

Eg Bottom:

function gameLoop() {
   renderFrameHere();

   RequestAnimationFrame(gameLoop);
}

Thank you,

Younger answered 16/5, 2016 at 13:43 Comment(1)
Does this answer your question? requestAnimationFrame at beginning or end of function? See also: Is requestAnimationFrame implementation's recursive?Alexandraalexandre
D
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>
Diorama answered 17/5, 2016 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.