2020-11-20 12:11:50 +08:00
|
|
|
import raf from 'rc-util/lib/raf';
|
2017-01-26 11:23:54 +08:00
|
|
|
|
2022-11-19 13:45:56 +08:00
|
|
|
type throttledFn = (...args: any[]) => void;
|
|
|
|
|
|
|
|
type throttledCancelFn = { cancel: () => void };
|
|
|
|
|
|
|
|
function throttleByAnimationFrame<T extends any[]>(fn: (...args: T) => void) {
|
2017-11-22 12:06:49 +08:00
|
|
|
let requestId: number | null;
|
2017-02-08 14:44:43 +08:00
|
|
|
|
2022-04-05 13:01:18 +08:00
|
|
|
const later = (args: T) => () => {
|
2017-02-08 14:44:43 +08:00
|
|
|
requestId = null;
|
|
|
|
fn(...args);
|
|
|
|
};
|
|
|
|
|
2022-11-19 13:45:56 +08:00
|
|
|
const throttled: throttledFn & throttledCancelFn = (...args: T) => {
|
2017-02-08 14:44:43 +08:00
|
|
|
if (requestId == null) {
|
2018-05-22 13:01:28 +08:00
|
|
|
requestId = raf(later(args));
|
2017-02-08 14:44:43 +08:00
|
|
|
}
|
2017-01-26 11:23:54 +08:00
|
|
|
};
|
2017-02-08 14:44:43 +08:00
|
|
|
|
2022-04-05 13:01:18 +08:00
|
|
|
throttled.cancel = () => {
|
|
|
|
raf.cancel(requestId!);
|
|
|
|
requestId = null;
|
|
|
|
};
|
2017-02-08 14:44:43 +08:00
|
|
|
|
|
|
|
return throttled;
|
2017-01-26 11:23:54 +08:00
|
|
|
}
|
|
|
|
|
2022-11-19 13:45:56 +08:00
|
|
|
export default throttleByAnimationFrame;
|