RequestAnimationFrame position in code

橙三吉。 提交于 2019-12-25 06:59:50

问题


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,


回答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>


来源:https://stackoverflow.com/questions/37255412/requestanimationframe-position-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!