Function call every x seconds in requestAnimationFrame

I am working on some kind of personal project Three.js. I am using the requestAnimationFrame function. I want to call a function every 2 seconds. I searched, but did not find anything useful. My code is as follows:

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

Any idea?

+6
source share
3 answers

requestAnimationFrame passes a single parameter to your callback that indicates the current time (in ms) when requestAnimationFrame triggered. You can use it to calculate the 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); } 
+3
source

Since requestAnimationFrame will provide you with an accessible frame with a resolution of 60 frames per second (if your browser is not behind it), it seems like it should wait 2 seconds and request a frame. Thus, the browser will provide you with 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); 
0
source

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

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

Ps 120 is not seconds, but frames.

0
source

Source: https://habr.com/ru/post/985504/


All Articles