Controlling FPS With requestAnimationFrame

I see lot of people asking this question on the internet. So here’s a quick tip that may help you.

Bit About rAF (requestAnimationFrame)

rAF function is the key to smooth JavaScript animations. rAF try its best to run the animation at 60fps. But sometimes that’s not what we want. So how can we use rAF with custom fps?

Custom FPS with rAF

rAF don’t have support for custom FPS so we have to make use of setTimeout to delay the call to requestAnimationFrame based on the fps we want to achieve.

const FPS = 30;
const DELAY = 1000 / FPS;
 
function draw() {
 
  // delay rAF according to DELAY
  setTimeout(function () {
    requestAnimationFrame(draw);
  }, DELAY);
 
  // draw your objects here...
 
}

That’s it!


comments powered by Disqus