Created
July 4, 2018 06:26
-
-
Save vlio20/61f88f51772b3f5a030277e5cb8e4355 to your computer and use it in GitHub Desktop.
typescript decorator for debounce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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