Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function each x second in requestAnimationFrame

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?

like image 614
Siamak Motlagh Avatar asked Apr 20 '15 09:04

Siamak Motlagh


2 Answers

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);
}
like image 171
hindmost Avatar answered Sep 30 '22 02:09

hindmost


this function will print a number every 2 seconds

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();
like image 30
Abdulnaser Avatar answered Sep 30 '22 01:09

Abdulnaser