@ozen-ui/kit
Version:
React component library
39 lines (38 loc) • 1.59 kB
JavaScript
import { __read, __spreadArray } from "tslib";
import { useCallback, useEffect, useRef } from 'react';
/** Хук для задержки вызова функции */
export function useDebounceCallback(callback, delay, options) {
if (delay === void 0) { delay = 300; }
if (options === void 0) { options = { firstCallWithoutDelay: false }; }
var firstCallWithoutDelay = options.firstCallWithoutDelay;
var timeoutRef = useRef(null);
var debouncedHandler = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!timeoutRef.current && firstCallWithoutDelay) {
callback.apply(void 0, __spreadArray([], __read(args), false));
timeoutRef.current = setTimeout(function () {
timeoutRef.current = null;
}, delay);
return;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(function () {
callback.apply(void 0, __spreadArray([], __read(args), false));
timeoutRef.current = null;
}, delay);
}, [callback, delay, options.firstCallWithoutDelay]);
var cancel = useCallback(function () {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
}, []);
useEffect(function () { return function () { return cancel(); }; }, []);
return [debouncedHandler, cancel];
}