UNPKG

mauss

Version:

practical functions and reusable configurations

38 lines (37 loc) 841 B
const DURATION = 300; /** * Immediately execute `fn` and block subsequent calls for `time` ms * * @example * ```js * onclick = () => immediate(() => {...}, 500); * ``` */ export function immediate(fn, time = DURATION) { let timeout; return (...args) => { if (timeout) return; fn(...args); timeout = setTimeout(() => clearTimeout(timeout), time); }; } /** * Allow `fn` to be called at most once every `time` ms * * @example * ```js * const search = throttle((query) => {...}, 500); * * onclick = () => search('mauss'); // execute every 500ms * ``` */ export function throttle(fn, time = DURATION) { let wait = false; return (...args) => { if (wait) return; fn(...args), (wait = true); setTimeout(() => (wait = false), time); }; }