@gdjiami/hooks
Version:
react hooks for mygzb.com
35 lines (34 loc) • 1.19 kB
JavaScript
import { __read, __spread } from "tslib";
import { useEffect } from 'react';
import useOnUnmount from './useOnUnmount';
import useInstance from './useInstance';
function useThrottle(fn, ms, args) {
if (ms === void 0) { ms = 200; }
if (args === void 0) { args = []; }
var _a = __read(useInstance({}), 1), state = _a[0];
useEffect(function () {
if (state.timeout == null) {
// first call
fn.apply(void 0, __spread(args));
var timeoutCallback_1 = function () {
if (state.hasNext) {
state.hasNext = false;
fn.apply(void 0, __spread(state.nextArgs));
state.timeout = window.setTimeout(timeoutCallback_1, ms);
}
else {
state.timeout = undefined;
}
};
state.timeout = window.setTimeout(timeoutCallback_1, ms);
}
else {
state.nextArgs = args;
state.hasNext = true;
}
}, args);
useOnUnmount(function () {
clearTimeout(state.timeout);
});
}
export default useThrottle;