@gdjiami/hooks
Version:
react hooks for mygzb.com
43 lines (36 loc) • 975 B
JavaScript
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 _useInstance = useInstance({}),
state = _useInstance[0];
useEffect(function () {
if (state.timeout == null) {
// first call
fn.apply(void 0, args);
var timeoutCallback = function timeoutCallback() {
if (state.hasNext) {
state.hasNext = false;
fn.apply(void 0, state.nextArgs);
state.timeout = window.setTimeout(timeoutCallback, ms);
} else {
state.timeout = undefined;
}
};
state.timeout = window.setTimeout(timeoutCallback, ms);
} else {
state.nextArgs = args;
state.hasNext = true;
}
}, args);
useOnUnmount(function () {
clearTimeout(state.timeout);
});
}
export default useThrottle;