在 requestAnimationFrame 中每 x 秒调用一个函数 [英] Call a function each x second in requestAnimationFrame

查看:31
本文介绍了在 requestAnimationFrame 中每 x 秒调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 Three.js 的一些个人项目.我正在使用 requestAnimationFrame 函数.我想每 2 秒调用一次函数.我已经搜索过了,但找不到任何有用的东西.

我的代码是这样的:

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

有什么想法吗?

推荐答案

requestAnimationFrame 将单个参数传递给您的回调,该参数指示 requestAnimationFrame 触发回调时的当前时间(以毫秒为单位).您可以使用它来计算 render() 调用之间的时间间隔.

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

这篇关于在 requestAnimationFrame 中每 x 秒调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆