A scheduler based on requestAnimationFrame that throttles function execution using the browser's animation frame timing
npx @tessl/cli install tessl/npm-raf-schd@4.0.0raf-schd is a throttle function that uses requestAnimationFrame to limit the rate at which a function is called. Unlike standard throttle functions that use fixed time intervals, raf-schd uses requestAnimationFrame for rate limiting, automatically adapting to the available browser resources and frame rate.
npm install raf-schdES6 Module:
import rafSchd from 'raf-schd';CommonJS:
const rafSchd = require('raf-schd').default;import rafSchd from 'raf-schd';
const expensiveFn = (arg) => {
console.log(arg);
};
const schedule = rafSchd(expensiveFn);
schedule('foo');
schedule('bar');
schedule('baz');
// animation frame fires
// => 'baz'Creates a throttled version of any function that will execute on the next animation frame with the latest arguments provided.
/**
* Creates a throttled function using requestAnimationFrame
* @param fn - Function to throttle (accepts any number of arguments)
* @returns Wrapper function with cancel method
*/
function rafSchd<T: $ReadOnlyArray<any>>(fn: (...T) => void): WrapperFn<T>;
type WrapperFn<T> = {
[[call]]: (...T) => void;
cancel: () => void;
};The returned wrapper function:
.cancel() method to prevent pending executionUsage Examples:
import rafSchd from 'raf-schd';
// Basic throttling
const doSomething = (value) => console.log(`Processing: ${value}`);
const schedule = rafSchd(doSomething);
schedule(1);
schedule(2);
schedule(3);
// Animation frame fires
// => Processing: 3
// Multiple arguments
const processUser = (name, age, email) => {
console.log(`User: ${name}, Age: ${age}, Email: ${email}`);
};
const scheduleProcess = rafSchd(processUser);
scheduleProcess('Alice', 25, 'alice@example.com');
scheduleProcess('Bob', 30, 'bob@example.com');
// Animation frame fires
// => User: Bob, Age: 30, Email: bob@example.com
// Optimized scroll listener
const handleScroll = (scrollY) => {
// Expensive scroll handling logic
console.log(`Scroll position: ${scrollY}`);
};
const scheduledScroll = rafSchd(handleScroll);
window.addEventListener('scroll', () => {
scheduledScroll(window.scrollY);
});Cancel a pending animation frame execution using the .cancel() method.
/**
* Cancel pending animation frame execution
* Only cancels if the frame has not yet executed
*/
cancel(): void;Usage Example:
const schedule = rafSchd(doSomething);
schedule('foo');
schedule.cancel(); // Cancels the pending execution
// doSomething will not be executed in the next animation frame/**
* Wrapper function type with callable interface and cancel method
* T represents the argument types array for the wrapped function
*/
type WrapperFn<T> = {
[[call]]: (...T) => void;
cancel: () => void;
};Requires requestAnimationFrame and cancelAnimationFrame APIs. Supported in all modern browsers.