2021-11-02 08:07:35 +00:00
|
|
|
import raf from './raf';
|
|
|
|
|
2020-10-13 14:26:56 +00:00
|
|
|
export default function throttleByAnimationFrame(fn: (...args: any[]) => void) {
|
2021-12-19 03:06:55 +00:00
|
|
|
let requestId: number;
|
2017-12-07 10:33:33 +00:00
|
|
|
|
2020-10-13 14:26:56 +00:00
|
|
|
const later = (args: any[]) => () => {
|
2019-01-12 03:33:27 +00:00
|
|
|
requestId = null;
|
|
|
|
fn(...args);
|
|
|
|
};
|
2017-12-07 10:33:33 +00:00
|
|
|
|
2020-10-13 14:26:56 +00:00
|
|
|
const throttled = (...args: any[]) => {
|
2017-12-07 10:33:33 +00:00
|
|
|
if (requestId == null) {
|
2021-11-02 08:07:35 +00:00
|
|
|
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
|
|
|
|
2021-11-02 08:07:35 +00:00
|
|
|
(throttled as any).cancel = () => raf.cancel(requestId!);
|
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
|
|
|
}
|
|
|
|
|
2019-01-12 03:33:27 +00:00
|
|
|
export function throttleByAnimationFrameDecorator() {
|
2020-10-13 14:26:56 +00:00
|
|
|
// eslint-disable-next-line func-names
|
2021-06-23 15:08:16 +00:00
|
|
|
return function (target: any, key: string, descriptor: any) {
|
2019-01-12 03:33:27 +00:00
|
|
|
const fn = descriptor.value;
|
|
|
|
let definingProperty = false;
|
2017-12-07 10:33:33 +00:00
|
|
|
return {
|
|
|
|
configurable: true,
|
2019-01-12 03:33:27 +00:00
|
|
|
get() {
|
2020-10-13 14:26:56 +00:00
|
|
|
// eslint-disable-next-line no-prototype-builtins
|
2017-12-07 10:33:33 +00:00
|
|
|
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
|
2019-01-12 03:33:27 +00:00
|
|
|
return fn;
|
2017-12-07 10:33:33 +00:00
|
|
|
}
|
|
|
|
|
2019-01-12 03:33:27 +00:00
|
|
|
const boundFn = throttleByAnimationFrame(fn.bind(this));
|
|
|
|
definingProperty = true;
|
2017-12-07 10:33:33 +00:00
|
|
|
Object.defineProperty(this, key, {
|
|
|
|
value: boundFn,
|
|
|
|
configurable: true,
|
|
|
|
writable: true,
|
2019-01-12 03:33:27 +00:00
|
|
|
});
|
|
|
|
definingProperty = false;
|
|
|
|
return boundFn;
|
2017-12-07 10:33:33 +00:00
|
|
|
},
|
2019-01-12 03:33:27 +00:00
|
|
|
};
|
|
|
|
};
|
2017-12-07 10:33:33 +00:00
|
|
|
}
|