typedash
Version:
modern, type-safe collection of utility functions
38 lines (37 loc) • 1.31 kB
JavaScript
//#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
export { debounce as t };
//# sourceMappingURL=debounce-qrP8tjIp.js.map