防抖:
export const useDebounce = (fn, delay = 500, dep = []) => {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
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)
}
节流:
export function useThrottle(fn, delay = 500, dep = []) {
const { current } = useRef({ fn, timer: null })
useEffect(function () {
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)
}
使用:
import { useDebounce, useThrottle } from '...'
const handleSearch = useDebounce(() => {
// todo something
}, 300)
const handleScroll = useThrottle(() => {
// todo something
}, 1500)}