You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
623 B
30 lines
623 B
4 years ago
|
import raf from 'rc-util/lib/raf';
|
||
8 years ago
|
|
||
2 years ago
|
type throttledFn = (...args: any[]) => void;
|
||
|
|
||
|
type throttledCancelFn = { cancel: () => void };
|
||
|
|
||
|
function throttleByAnimationFrame<T extends any[]>(fn: (...args: T) => void) {
|
||
7 years ago
|
let requestId: number | null;
|
||
8 years ago
|
|
||
3 years ago
|
const later = (args: T) => () => {
|
||
8 years ago
|
requestId = null;
|
||
|
fn(...args);
|
||
|
};
|
||
|
|
||
2 years ago
|
const throttled: throttledFn & throttledCancelFn = (...args: T) => {
|
||
8 years ago
|
if (requestId == null) {
|
||
7 years ago
|
requestId = raf(later(args));
|
||
8 years ago
|
}
|
||
8 years ago
|
};
|
||
8 years ago
|
|
||
3 years ago
|
throttled.cancel = () => {
|
||
|
raf.cancel(requestId!);
|
||
|
requestId = null;
|
||
|
};
|
||
8 years ago
|
|
||
|
return throttled;
|
||
8 years ago
|
}
|
||
|
|
||
2 years ago
|
export default throttleByAnimationFrame;
|