UNPKG

@ozen-ui/kit

Version:

React component library

42 lines (41 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDebounceCallback = useDebounceCallback; var tslib_1 = require("tslib"); var react_1 = require("react"); /** Хук для задержки вызова функции */ function useDebounceCallback(callback, delay, options) { if (delay === void 0) { delay = 300; } if (options === void 0) { options = { firstCallWithoutDelay: false }; } var firstCallWithoutDelay = options.firstCallWithoutDelay; var timeoutRef = (0, react_1.useRef)(null); var debouncedHandler = (0, react_1.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, tslib_1.__spreadArray([], tslib_1.__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, tslib_1.__spreadArray([], tslib_1.__read(args), false)); timeoutRef.current = null; }, delay); }, [callback, delay, options.firstCallWithoutDelay]); var cancel = (0, react_1.useCallback)(function () { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }, []); (0, react_1.useEffect)(function () { return function () { return cancel(); }; }, []); return [debouncedHandler, cancel]; }