ant-design/components/_util/throttleByAnimationFrame.tsx

48 lines
1.2 KiB
TypeScript
Raw Normal View History

import raf from 'raf';
2018-03-06 21:28:54 +08:00
export default function throttleByAnimationFrame(fn: (...args: any[]) => void) {
2017-11-22 12:06:49 +08:00
let requestId: number | null;
2017-11-22 12:06:49 +08:00
const later = (args: any[]) => () => {
requestId = null;
fn(...args);
};
2017-11-22 12:06:49 +08:00
const throttled = (...args: any[]) => {
if (requestId == null) {
requestId = raf(later(args));
}
};
(throttled as any).cancel = () => raf.cancel(requestId!);
return throttled;
}
export function throttleByAnimationFrameDecorator() {
2019-08-11 19:38:08 +08:00
// eslint-disable-next-line func-names
2017-11-22 12:06:49 +08:00
return function(target: any, key: string, descriptor: any) {
2018-11-10 00:38:06 +08:00
const fn = descriptor.value;
let definingProperty = false;
return {
configurable: true,
get() {
// eslint-disable-next-line no-prototype-builtins
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
return fn;
}
2018-11-10 00:38:06 +08:00
const boundFn = throttleByAnimationFrame(fn.bind(this));
definingProperty = true;
Object.defineProperty(this, key, {
value: boundFn,
configurable: true,
writable: true,
});
definingProperty = false;
return boundFn;
},
};
};
}