2019-01-12 11:33:27 +08:00
|
|
|
import raf from 'raf';
|
2017-12-07 18:33:33 +08:00
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
export default function throttleByAnimationFrame(fn) {
|
|
|
|
let requestId;
|
2017-12-07 18:33:33 +08:00
|
|
|
|
|
|
|
const later = args => () => {
|
2019-01-12 11:33:27 +08:00
|
|
|
requestId = null;
|
|
|
|
fn(...args);
|
|
|
|
};
|
2017-12-07 18:33:33 +08:00
|
|
|
|
|
|
|
const throttled = (...args) => {
|
|
|
|
if (requestId == null) {
|
2019-01-12 11:33:27 +08:00
|
|
|
requestId = raf(later(args));
|
2017-12-07 18:33:33 +08:00
|
|
|
}
|
2019-01-12 11:33:27 +08:00
|
|
|
};
|
2017-12-07 18:33:33 +08:00
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
throttled.cancel = () => raf.cancel(requestId);
|
2017-12-07 18:33:33 +08:00
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
return throttled;
|
2017-12-07 18:33:33 +08:00
|
|
|
}
|
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
export function throttleByAnimationFrameDecorator() {
|
|
|
|
return function(target, key, descriptor) {
|
|
|
|
const fn = descriptor.value;
|
|
|
|
let definingProperty = false;
|
2017-12-07 18:33:33 +08:00
|
|
|
return {
|
|
|
|
configurable: true,
|
2019-01-12 11:33:27 +08:00
|
|
|
get() {
|
2017-12-07 18:33:33 +08:00
|
|
|
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
|
2019-01-12 11:33:27 +08:00
|
|
|
return fn;
|
2017-12-07 18:33:33 +08:00
|
|
|
}
|
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
const boundFn = throttleByAnimationFrame(fn.bind(this));
|
|
|
|
definingProperty = true;
|
2017-12-07 18:33:33 +08:00
|
|
|
Object.defineProperty(this, key, {
|
|
|
|
value: boundFn,
|
|
|
|
configurable: true,
|
|
|
|
writable: true,
|
2019-01-12 11:33:27 +08:00
|
|
|
});
|
|
|
|
definingProperty = false;
|
|
|
|
return boundFn;
|
2017-12-07 18:33:33 +08:00
|
|
|
},
|
2019-01-12 11:33:27 +08:00
|
|
|
};
|
|
|
|
};
|
2017-12-07 18:33:33 +08:00
|
|
|
}
|