Last active
October 16, 2020 20:11
-
-
Save dmjcomdem/53bd69b48d977e0d8635b4993e91efb1 to your computer and use it in GitHub Desktop.
Creates a debounced function that delays invoking the provided function
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
type DebounceFunc = (...args: any[]) => void; | |
/** | |
* Creates a debounced function that delays invoking the provided function | |
* @param {Function} func - The function to debounce wait. | |
* @param {number} ms - The number of milliseconds to delay. | |
* @returns {Function} Returns the new debounced function. | |
*/ | |
function debounce<F extends DebounceFunc>(func: F, ms: number) { | |
let timeout: ReturnType<typeof setTimeout>; | |
const debounced = (...args: Parameters<F>) => { | |
clearTimeout(timeout); | |
timeout = setTimeout(() => func(...args), ms); | |
}; | |
return debounced as (...args: Parameters<F>) => ReturnType<F>; | |
}; | |
/** | |
* Logger | |
*/ | |
const logger = (name: keyof Window): void => console.log(window[name]); | |
window.addEventListener( | |
'resize', | |
(event: UIEvent) => debounce(logger, 500)('innerWidth') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment