DEV Community

Kenneth Lum
Kenneth Lum

Posted on

Auto repeat requestAnimationFrame()

We have requestAnimationFrame(), but it is like setTimeout(): we have to keep calling it.

Can we have something that is more like setInterval(), something we can "set it, and forget it"?

We can write our own routine:

        function requestAnimationFrameRepeat(fn) {
          let continueToUpdate = true;

          function updater() {
            if (continueToUpdate) {
              fn();
              requestAnimationFrame(updater);
            }
          }

          requestAnimationFrame(updater);

          return function () {
            continueToUpdate = false;
          };
        }
Enter fullscreen mode Exit fullscreen mode

So instead of calling requestAnimationFrame(ourUpdateFunction), which is for one time only, we can call requestAnimationFrameRepeat(ourUpdateFunction) and get back a function stopTheUpdateFn.

Then ourUpdateFunction will be invoked automatically, every time before the JS engine is updating what is to be shown on screen.

And when we want it to stop, simply call stopTheUpdateFn by stopTheUpdateFn(), and it will stop, immediately, with the next upcoming update not to be run at all.

Top comments (0)