在React中防抖实现

582 阅读1分钟

1.背景

​ 用户在页面上频繁点击查询按钮大数据量内容,后端服务器内存溢出。

2.实现原理

​ 在第一次触发事件时,不立即执行函数,而是给出一个期限值

​ 实现代码如下:

const debounce = (func, delay) => {
  let timeout;
  return () => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(function () {
      func();
    }, delay);
  }
}


const log = debounce(()=>{console.log("1")},500);
log();
log();
log();

运行结果如下:

Snipaste_2021-04-19_14-26-28.png

3.适用场景

  • 搜索框input事件
    
  • 页面resize事件
    

4.在React中实现防抖

export const useDebounce = (value, delay) => {
    const [debounceValue, setDebounceValue] = useState(value)
    useEffect(() => {
        const timeout = setTimeout(() => setDebounceValue(value), delay)
        return () => clearTimeout(timeout)
    }, [value, delay])
    return debounceValue
}