Skip to content

Instantly share code, notes, and snippets.

@dmjcomdem
Last active October 16, 2020 20:11
Show Gist options
  • Save dmjcomdem/53bd69b48d977e0d8635b4993e91efb1 to your computer and use it in GitHub Desktop.
Save dmjcomdem/53bd69b48d977e0d8635b4993e91efb1 to your computer and use it in GitHub Desktop.
Creates a debounced function that delays invoking the provided function
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