ht_hooks
Version:
ht React 业务 Hooks
37 lines • 1.1 kB
JavaScript
import { __read } from "tslib";
import { useEffect, useState, useCallback } from 'react';
import useThrottleFn from '../useThrottleFn';
function useThrottle(value, options) {
var _a = __read(useState(value), 2),
throttled = _a[0],
setThrottled = _a[1];
var run = useThrottleFn(function () {
setThrottled(value);
}, options).run;
useEffect(function () {
run();
}, [value]);
return throttled;
}
export default useThrottle;
// const useThrottle2=(callback:Callback,delay:number=500)=>{
// const throttleCallback=()=>{
// }
// }
function useThrottle3(fn, t) {
var timer = null;
useEffect(function () {
return function () {
if (timer) clearTimeout(timer);
};
});
return useCallback(function () {
if (!timer) {
//#若timer有值说明正在计时中则什么都不做,若timer没值(计时结束定时器自动清除,timer手动清空)说明此时无计时,则开启定时,结束后执行然后关闭定时器
timer = setTimeout(function () {
fn();
timer = null;
}, t);
}
}, [timer, fn, t]);
}