DEV Community

Kenneth Lum
Kenneth Lum

Posted on

3 2

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay