UNPKG

@microsoft/windows-admin-center-sdk

Version:

Microsoft - Windows Admin Center Shell

50 lines (48 loc) 2.41 kB
/** * Constant key for the property that we auto-magically inject into decorated class instances to manage timout references. * the value should be unique enough to never conflict with realistic property names in a class. */ const smeDebounceTimeoutRefKey = '__SmeDebounceDecoratorCurrentTimeoutReference__'; /* * @Debounce() Method Decorator * Ensures a method is only executed at a maximum of 1 time per every delay interval. * Note: this only works with functions that return void. The delay makes it impossible to return values in the * same context as the function was originally executed. * @param delay The amount of time in milliseconds to debounce the method. Defaults to 200ms * @param immediateExecution If true, will execute the original method before timeout instead of afterwards. Defaults to false * @returns A @see MethodDecorator for the method that this is decorating */ export function Debounce(delay = 200, immediateExecution = false) { // eslint-disable-next-line unused-imports/no-unused-vars return (target, propertyKey, descriptor) => { // copy the descriptor const method = { ...descriptor }; // remember the old value const value = method.value; // create a new value that debounces calls method.value = function (...args) { const instance = this; let currentTimoutRef = instance[smeDebounceTimeoutRefKey]; /// if there is a timer then clear it. if (!MsftSme.isNullOrUndefined(currentTimoutRef)) { clearTimeout(currentTimoutRef); } else if (immediateExecution) { /// if there is a no timer and we were supposed to execute immediately, // then call the original method before setting a timeout value.apply(instance, args); } // start a new timeout instance[smeDebounceTimeoutRefKey] = setTimeout(() => { // when the timeout completes, clear our reference to it. currentTimoutRef = null; // if we did not start with execution, then execute now by calling the original method if (!immediateExecution) { value.apply(instance, args); } }, delay); }; return method; }; } //# sourceMappingURL=debounce.decorators.js.map