UNPKG

@boost/decorators

Version:

Experimental decorators for common patterns.

35 lines (30 loc) 1.13 kB
import { isMethod } from './helpers/isMethod.mjs'; /** * A method decorator that throttles the execution of a class method to * only fire once within every delay timeframe (in milliseconds). */ function Throttle(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(`\`@Throttle\` may only be applied to class methods.`); } // We must use a map as all class instances would share the // same boolean value otherwise. const throttling = new WeakMap(); // Overwrite the value function with a new throttled function const func = descriptor.value; // @ts-expect-error Override generic descriptor.value = function throttle(...args) { if (throttling.get(this)) { return; } func.apply(this, args); throttling.set(this, true); setTimeout(() => { throttling.delete(this); }, delay); }; }; } export { Throttle }; //# sourceMappingURL=Throttle.mjs.map