Files
ETB/ETB-FrontEnd/node_modules/@mui/x-internals/esm/rafThrottle/rafThrottle.js
Iliyan Angelov 306b20e24a Frontend start
2025-09-14 00:54:48 +03:00

33 lines
765 B
JavaScript

/**
* Creates a throttled function that only invokes `fn` at most once per animation frame.
*
* @example
* ```ts
* const throttled = rafThrottle((value: number) => console.log(value));
* window.addEventListener('scroll', (e) => throttled(e.target.scrollTop));
* ```
*
* @param fn Callback function
* @return The `requestAnimationFrame` throttled function
*/
export function rafThrottle(fn) {
let lastArgs;
let rafRef;
const later = () => {
rafRef = null;
fn(...lastArgs);
};
function throttled(...args) {
lastArgs = args;
if (!rafRef) {
rafRef = requestAnimationFrame(later);
}
}
throttled.clear = () => {
if (rafRef) {
cancelAnimationFrame(rafRef);
rafRef = null;
}
};
return throttled;
}