Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - requestAnimationFrame at beginning or end of function?

If I have a loop using requestAnimationFrame like this:

function render() {
    // Rendering code

    requestAnimationFrame(render);
}

Will there be any difference if I put the requestAnimationFrame in the beginning of the function, like this:

function render() {
    requestAnimationFrame(render);

    // Rendering code
}

I haven't noticed any difference, but I have seen both implementations, is one of them better in any way, or are they the same?

Edit: One thing I have thought about is, if I put it in the beginning, and the render code takes quite long time to run, say 10ms, wouldn't putting it in the end make the frame rate drop with 10ms?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

requestAnimationFrame does always call its callback asynchronously, so as long as your rendering code is synchronous and does not throw exceptions it doesn't make any difference.

It's essentially a style choice, choose yourself which approach is cleaner. Putting it at the top may emphasise that render is scheduling itself, and does so even in the presence of errors in the rendering. Putting it in the bottom allows to conditionally break out of the rendering loop (e.g. when you want to pause your game).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...