@boost/decorators
Version:
Experimental decorators for common patterns.
35 lines (30 loc) • 1.11 kB
JavaScript
import { isMethod } from './helpers/isMethod.mjs';
/**
* A method decorator that delays the execution of the class method
* by the provided time in milliseconds.
*/
function Debounce(delay) {
return (target, property, descriptor) => {
if (process.env.NODE_ENV !== "production" && (!isMethod(target, property, descriptor) || !('value' in descriptor && typeof descriptor.value === 'function'))) {
throw new TypeError(`\`@Debounce\` may only be applied to class methods.`);
}
// We must use a map as all class instances would share the
// same timer value otherwise.
const timers = new WeakMap();
// Overwrite the value function with a new debounced function
const func = descriptor.value;
// @ts-expect-error Override generic
descriptor.value = function debounce(...args) {
const timer = timers.get(this);
if (timer) {
clearTimeout(timer);
timers.delete(this);
}
timers.set(this, setTimeout(() => {
func.apply(this, args);
}, delay));
};
};
}
export { Debounce };
//# sourceMappingURL=Debounce.mjs.map