Skip to main content

README

防抖

export const useDebounce = (fn, delay, dep = []) => {
const { current } = useRef({ fn, timer: null });

useEffect(() => {
current.fn = fn;
}, [fn]);

return useCallback(function f(...args) {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(() => {
current.fn.call(this, ...args);
}, delay);
}, dep);
};
const handlerSearch = useDebounce(() => {
console.log("嘿嘿");
}, 1000);

节流

const useThrottle = (fn, delay, dep = []) => {
const { current } = useRef({ fn, timer: null });

useEffect(() => {
current.fn = fn;
}, [fn]);

return useCallback(function f(...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
current.fn.call(this, ...args);
}
}, dep);
};
const handlerSearch = useThrottle(() => {
console.log("嘿嘿");
}, 1000);

链接