Call a function each x second in requestAnimationFrame

别来无恙 提交于 2019-11-30 14:57:15

问题


I'm working on some personal project by Three.js. I'm using requestAnimationFrame function. I want to call a function each 2 seconds. I've search but I couldn't find anything useful.

My code is like this:

function render() {
   // each 2 seconds call the createNewObject() function
   if(eachTwoSecond) {
      createNewObject();
   }
   requestAnimationFrame(render);
   renderer.render(scene, camera);
}

Any Idea?


回答1:


requestAnimationFrame passes single parameter to your callback which indicates the current time (in ms) when requestAnimationFrame fires the callback. You can use it to calculate time interval between render() calls.

var last = 0; // timestamp of the last render() call
function render(now) {
    // each 2 seconds call the createNewObject() function
    if(!last || now - last >= 2*1000) {
        last = now;
        createNewObject();
    }
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}



回答2:


Since requestAnimationFrame will give you an available frame in 60fps (if your browser can keep up with it) it seems perfectly fine to wait 2 seconds and request a frame. This way the browser will give you a frame exactly after these 2 seconds, which in most cases will be in an instant:

        function render() {
            // each 2 seconds call the createNewObject() function
            createNewObject();
            renderer.render(scene, camera);
        }

        setInterval(function () {
            requestAnimationFrame(render);
        }, 2000);



回答3:


I had a similar problem and came up with this solution:

let i = 0
function render() {
   if (++i % 120 == 0) doSomething()
   requestAnimationFrame(render)
}

P.s. 120 is not seconds but frames.



来源:https://stackoverflow.com/questions/29743592/call-a-function-each-x-second-in-requestanimationframe

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