ant-design-vue/components/_util/throttleByAnimationFrame.ts

30 lines
613 B
TypeScript
Raw Normal View History

import raf from './raf';
2023-01-26 14:14:20 +00:00
type throttledFn = (...args: any[]) => void;
type throttledCancelFn = { cancel: () => void };
function throttleByAnimationFrame<T extends any[]>(fn: (...args: T) => void) {
2022-05-10 07:36:18 +00:00
let requestId: number | null;
2017-12-07 10:33:33 +00:00
2022-05-10 07:36:18 +00:00
const later = (args: T) => () => {
2019-01-12 03:33:27 +00:00
requestId = null;
fn(...args);
};
2017-12-07 10:33:33 +00:00
2023-01-26 14:14:20 +00:00
const throttled: throttledFn & throttledCancelFn = (...args: T) => {
2017-12-07 10:33:33 +00:00
if (requestId == null) {
requestId = raf(later(args));
2017-12-07 10:33:33 +00:00
}
2019-01-12 03:33:27 +00:00
};
2017-12-07 10:33:33 +00:00
2022-05-10 07:36:18 +00:00
throttled.cancel = () => {
raf.cancel(requestId!);
requestId = null;
};
2017-12-07 10:33:33 +00:00
2019-01-12 03:33:27 +00:00
return throttled;
2017-12-07 10:33:33 +00:00
}
2023-01-26 14:14:20 +00:00
export default throttleByAnimationFrame;