背景
用户使用软件时,因为网络或者是硬件的问题导致点击按钮没反应,使客户端多次向客户端发送请求,为了减少服务器的压力,或者某些不怀好意的用户多次点击,增加服务器压力,可以使用防抖节流达到此目的,下面一个是平时我常用的封装好的节流函数。
代码
可以在utils中写一个帮助方法,这样可以多次使用
// 防抖
export function useDebounce(fn, delay, 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, 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 { useThrottle,useDebounce } from "../../utils/helper";
const handlerSearch = useThrottle(() => {console.log('嘿嘿')},1000)
const handlerSearch = useDebounce(() => {console.log('嘿嘿')},1000)