Skip to content

Instantly share code, notes, and snippets.

@vlio20
Created July 4, 2018 06:26
Show Gist options
  • Save vlio20/61f88f51772b3f5a030277e5cb8e4355 to your computer and use it in GitHub Desktop.
Save vlio20/61f88f51772b3f5a030277e5cb8e4355 to your computer and use it in GitHub Desktop.
typescript decorator for debounce
export const DEFAULT_DEBOUNCE_MS = 500;
export function debounce(ms: number = DEFAULT_DEBOUNCE_MS): Function {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): any {
return {
configurable: true,
enumerable: descriptor.enumerable,
get: function (): () => any {
Object.defineProperty(this, propertyKey, {
configurable: true,
enumerable: descriptor.enumerable,
value: _debounce(descriptor.value, ms)
});
return this[propertyKey];
}
};
};
}
function _debounce(func: Function, ms: number): Function {
let timeoutId: any;
return function () {
const context = this;
const args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
func.apply(context, args);
}, ms);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment