在 requestAnimationFrame 中每隔 x 秒调用一个函数

Call a function each x second in requestAnimationFrame

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

我的代码是这样的:

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

有什么想法吗?

因为 requestAnimationFrame 会给你一个 60fps 的可用帧(如果你的浏览器可以跟上它)等待 2 秒并请求一个帧似乎完全没问题。这样浏览器就会在这 2 秒后给你一个框架,在大多数情况下会在瞬间:

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

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

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

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

我遇到了类似的问题并提出了这个解决方案:

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

P.s。 120 不是秒而是帧。

此函数将每 2 秒打印一个数字

let last = 0;
let num = 0;
let speed = 2;

function main(timeStamp) {
  let timeInSecond = timeStamp / 1000;

  if (timeInSecond - last >= speed) {
    last = timeInSecond;
    console.log(++num);
  }

  requestAnimationFrame(main);
}

main();

每给定秒运行一次的简单 JS 计时器

修改MDN示例--> Here.

/*
<div id="test">
        <h1>Hello World</h1>
</div>
*/
const element = document.getElementById('test');
let start, previousTimeStamp;


timerConfig = {
    frequency: 1, // Seconds
    stopAt: 10, // Seconds,
    pos: 1,  // px
    posStep: 10,  // px
    updatePos: () => {
        timerConfig.pos = timerConfig.pos + timerConfig.posStep;
    }
}

function timer(timestamp) {    
    if (start === undefined)  start = timestamp;
    if (previousTimeStamp === undefined)  previousTimeStamp = timestamp;
    const seconds = timerConfig.frequency*1000;
    const tick = timestamp - previousTimeStamp; 

    function trigger() {
        element.style.transform = 'translateX(' + timerConfig.pos + 'px)';
    }

    if (tick >= seconds) {
        trigger();
        previousTimeStamp = timestamp; // Updating The Timer each second
        timerConfig.updatePos();
    }
    if (timestamp < timerConfig.stopAt*1000) requestAnimationFrame(timer); // 10 Seconds    
    
}

requestAnimationFrame(timer);