UNPKG

typedash

Version:

modern, type-safe collection of utility functions

44 lines (42 loc) 1.4 kB
//#region src/functions/debounce/debounce.ts /** * Creates a debounced function that delays invoking `func` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. * @param func The function to debounce. * @param delay The number of milliseconds to delay. * @param options Optional configuration options. * @param options.leading Whether to call the function on the leading edge of the timeout. * @returns A debounced function that can be called multiple times, but only invokes `func` once per `delay` milliseconds. */ function debounce(func, delay, options = {}) { let timeoutId = null; let isCalled = false; let latestArguments; function debouncedFunction(...args) { latestArguments = args; if (options.leading && !isCalled) { func(...args); isCalled = true; } if (timeoutId !== null) clearTimeout(timeoutId); timeoutId = setTimeout(() => { if (!options.leading) func(...args); isCalled = false; }, delay); } debouncedFunction.flush = () => { if (timeoutId !== null) clearTimeout(timeoutId); func(...latestArguments); }; debouncedFunction.clear = () => { if (timeoutId !== null) clearTimeout(timeoutId); }; return debouncedFunction; } //#endregion Object.defineProperty(exports, 'debounce', { enumerable: true, get: function () { return debounce; } }); //# sourceMappingURL=debounce-DlDzKYqG.cjs.map