rafu

1.2.0 · active · verified Sun Apr 19

rafu is a lightweight JavaScript utility that provides a `requestAnimationFrame` shim and enhanced animation scheduling capabilities. It ensures that animations run smoothly and efficiently across different browser environments by offering a robust fallback for `requestAnimationFrame` where native support might be missing or prefixed. Beyond merely polyfilling, rafu includes a `throttled` utility for synchronizing function calls with the browser's repaint cycle, which is crucial for performance-sensitive tasks like scroll handling, resize events, or continuous input processing. The package is currently at version 1.2.0, with its latest update introducing explicit cancellation methods for both direct `rafu` calls and functions created with `rafu.throttled`. Its minimal footprint and focused functionality make it a straightforward choice for projects needing basic `requestAnimationFrame` management without introducing heavy dependencies.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates scheduling a simple animation loop with `rafu` and throttling a scroll event handler using `rafu.throttled`.

import rafu from 'rafu';

const box = document.createElement('div');
box.style.width = '50px';
box.style.height = '50px';
box.style.backgroundColor = 'red';
box.style.position = 'absolute';
box.style.top = '0px';
box.style.left = '0px';
document.body.appendChild(box);

let posX = 0;
let direction = 1;

function animateBox() {
  posX += direction * 2;
  if (posX > window.innerWidth - 50 || posX < 0) {
    direction *= -1;
  }
  box.style.left = `${posX}px`;
  rafu(animateBox); // Schedule the next frame
}

animateBox(); // Start the animation loop

// Example of throttling a scroll event
const scrollHandler = () => {
  console.log('Scroll event throttled by rafu:', window.scrollY);
};

const throttledScrollHandler = rafu.throttled(scrollHandler);
window.addEventListener('scroll', throttledScrollHandler);

// To stop the animation after some time (demonstrating rafu.cancel)
setTimeout(() => {
  const animationId = rafu(() => console.log('This will be cancelled'));
  rafu.cancel(animationId);
  console.log('Animation scheduled and then cancelled.');
  window.removeEventListener('scroll', throttledScrollHandler);
  console.log('Scroll handler removed.');
}, 5000);

view raw JSON →