2017-02-08 14:44:43 +08:00
|
|
|
import getRequestAnimationFrame, { cancelRequestAnimationFrame } from '../_util/getRequestAnimationFrame';
|
2017-01-26 11:23:54 +08:00
|
|
|
|
|
|
|
const reqAnimFrame = getRequestAnimationFrame();
|
|
|
|
|
2017-02-08 14:44:43 +08:00
|
|
|
export default function throttleByAnimationFrame(fn) {
|
|
|
|
let requestId;
|
|
|
|
|
|
|
|
const later = args => () => {
|
|
|
|
requestId = null;
|
|
|
|
fn(...args);
|
|
|
|
};
|
|
|
|
|
|
|
|
const throttled = (...args) => {
|
|
|
|
if (requestId == null) {
|
|
|
|
requestId = reqAnimFrame(later(args));
|
|
|
|
}
|
2017-01-26 11:23:54 +08:00
|
|
|
};
|
2017-02-08 14:44:43 +08:00
|
|
|
|
|
|
|
(throttled as any).cancel = () => cancelRequestAnimationFrame(requestId);
|
|
|
|
|
|
|
|
return throttled;
|
2017-01-26 11:23:54 +08:00
|
|
|
}
|
|
|
|
|
2017-02-08 14:44:43 +08:00
|
|
|
export function throttleByAnimationFrameDecorator() {
|
2017-01-26 11:23:54 +08:00
|
|
|
return function(target, key, descriptor) {
|
|
|
|
let fn = descriptor.value;
|
|
|
|
let definingProperty = false;
|
|
|
|
return {
|
|
|
|
configurable: true,
|
|
|
|
get() {
|
|
|
|
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
|
|
|
|
return fn;
|
|
|
|
}
|
|
|
|
|
2017-02-08 14:44:43 +08:00
|
|
|
let boundFn = throttleByAnimationFrame(fn.bind(this));
|
2017-01-26 11:23:54 +08:00
|
|
|
definingProperty = true;
|
|
|
|
Object.defineProperty(this, key, {
|
|
|
|
value: boundFn,
|
|
|
|
configurable: true,
|
|
|
|
writable: true,
|
|
|
|
});
|
|
|
|
definingProperty = false;
|
|
|
|
return boundFn;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
};
|
|
|
|
}
|