@react-cmpt/use-throttle
Version:
The throttled value / function hook for react
62 lines (61 loc) • 1.97 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
/**
* useThrottleFn
*
* @param fn function
* @param wait number @default 0
* @param options object
*/
function useThrottleFn(fn, wait, options) {
if (wait === void 0) { wait = 0; }
var timer = (0, react_1.useRef)();
var fnRef = (0, react_1.useRef)(fn);
var optionsRef = (0, react_1.useRef)(options);
var currentArgs = (0, react_1.useRef)();
fnRef.current = fn;
optionsRef.current = options;
var cancel = (0, react_1.useCallback)(function () {
if (timer.current) {
clearTimeout(timer.current);
}
timer.current = undefined;
}, []);
var callback = (0, react_1.useCallback)(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
currentArgs.current = args;
if (!timer.current) {
if ((_a = optionsRef.current) === null || _a === void 0 ? void 0 : _a.leading) {
fnRef.current.apply(fnRef, currentArgs.current);
timer.current = setTimeout(function () {
timer.current = undefined;
}, wait);
}
else {
timer.current = setTimeout(function () {
fnRef.current.apply(fnRef, currentArgs.current);
timer.current = undefined;
}, wait);
}
}
}, [wait]);
var callPending = (0, react_1.useCallback)(function () {
if (!timer.current) {
return;
}
fnRef.current.apply(fnRef, currentArgs.current);
cancel();
}, [cancel]);
(0, react_1.useEffect)(function () { return cancel; }, [cancel]);
return {
callback: callback,
cancel: cancel,
callPending: callPending,
};
}
exports.default = useThrottleFn;
;