requestAnimationFrame implementation recursive?

2020-07-17 15:35发布

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?

3条回答
何必那么认真
2楼-- · 2020-07-17 15:38

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楼-- · 2020-07-17 15:42

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.

查看更多
来,给爷笑一个
4楼-- · 2020-07-17 15:46

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);

}
查看更多
登录 后发表回答