@taro-hooks/ahooks
Version:
37 lines • 1.17 kB
JavaScript
import { throttle } from 'lodash-wechat';
import { useMemo } from '@taro-hooks/core';
import useLatest from '../useLatest';
import useUnmount from '../useUnmount';
function useThrottleFn(fn, options) {
var _options$wait;
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
console.error("useThrottleFn expected parameter is a function, got " + typeof fn);
}
}
var fnRef = useLatest(fn);
var wait = (_options$wait = options == null ? void 0 : options.wait) != null ? _options$wait : 1000;
var throttled = useMemo(function () {
return (
// @ts-ignore
throttle(function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return fnRef == null ? void 0 : fnRef.current == null ? void 0 : fnRef.current.apply(fnRef, args);
}, wait, options)
);
}, []);
useUnmount(function () {
// @ts-ignore
throttled.cancel();
});
return {
run: throttled,
// @ts-ignore
cancel: throttled.cancel,
// @ts-ignore
flush: throttled.flush
};
}
export default useThrottleFn;