Debounce a function
JavaScript
/**
* Returns a debounced version of `fn` that delays invocation
* until `wait` ms have passed since the last call.
*/
export function debounce(fn, wait = 200) {
let timer;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
fn.apply(this, args);
}, wait);
}
debounced.cancel = () => {
clearTimeout(timer);
timer = undefined;
};
return debounced;
}