requestAnimationFrame implementation recursive?

2020-07-17 15:16发布

问题:

I'm currently experimenting with three.js, which relies on requestAnimationFrame to perform animations.

Question: Wouldn't the following code result in infinite recursion before the cube rotations and renderer.render function invocation?

function render() {
    requestAnimationFrame(render);
    cube.rotation.x += 0.1;
    cube.rotation.y += 0.1;
    renderer.render(scene, camera); 
}
render();

The code works, but I'm trying to improve my overall understanding of javascript.

The way I see it, is that render is invoked as a callback function. But does that mean that javascript continues running through the code in the function before stopping to move on to the next call?

回答1:

This only requests the browser to call your callback before the next rendering loop:

You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint.

So there is no recursion here, and your function continue with the execution.

You can also cancel the request for your callback with cancelAnimationFrame.

Look here.



回答2:

The simplest usage of requestanimationframe is to call it again and again until it is not necessary

I learned this lesson while I develop a small library

https://github.com/allenhwkim/jsanimation

Usage

import {slideInRight} from 'jsanimation';
slideInRight(el);


回答3:

After the first render() call, RequestAnimationFrame will asynchronously take care of your render function calling it every ~60 times per second. Your function is not recursive, since Javascript will continue the code execution.

However, you should use RequestAnimationFrame only at the very end of your render function, as last command of your function. Imagine you having a big scene, with a lot of animations: requesting the next frame before completing parameters update, will probably cause a huge mess.

You can also use setTimeout to handle your animations, calling the render method with the desired frame rate, like this:

var desideredFrameRate = 60;

window.myRequestAnimationFrame = function(callback) {

    setTimeout(callback, 1000/desiredFrameRate);

}