Timing Controls - Part 3

This is small one.

In a previous post, we looked at higher order implementations of the techniques discussed in another post.

In this post, we’ll look at requestAnimationFrame.

We use requestAnimationFrame when we have some repaint task - something that will change content on screen. But that’s just the general way of working things out.

function render() {
  // do something
  window.requestAnimationFrame(render);
}

window.requestAnimationFrame(render);

HighResTimeStamp

The problem with requestAnimationFrame is that it doesn’t enforce a callback speed - it only defines the upper limit of it. As MDN puts it:

The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.

The solution is easy. requestAnimationFrame passes a single argument to the callback function. It is a high resolution timestamp, measured in milliseconds.

We can use requestAnimationFrame as an alternative to setTimeout for our Throttle implementation.

function throttle(fn, delta, context) {
  return (...args) => {
    let then = 0;

    function repeat(now) {
      requestAnimationFrame(repeat);
      if (now - then >= delta) {
        then = now;
        fn.apply(context, args);
      }
    }

    requestAnimationFrame(repeat);
  };
}

And done. Throttle with requestAnimationFrame.

The code is available here.