防抖节流的hook封装

在页面中很多情况需要用到防抖和节流来优化系统性能,避免了函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。

主要是利用定时器来实现这两个功能

使用时只需要传来定义的类和触发时间即可

可以使用在

防抖:搜索框搜索输入,手机号、邮箱验证输入检测窗口大小resize。只需窗口调整完成后,计算窗口大小。防止重复渲染

节流:滚动加载,加载更多或滚到底部监听,防止

鼠标重复点击触发,

首先是防抖

export function useDebounce(){
    const debounce=(fn,delay)=>{
     let timer=null
     return function (){
         if(timer) clearTimeout(timer)
         timer =setTimeout(()=>{
         fn.apply(this,aarguments)
         },delay)
       }  
     }
     return {debounce}
}

然后是节流

export function useThrottle() {
   const throttle =(fn,delay)=>{
       let timer=null
        return function(){
        if(!timer){
            timer=setTimeout(()=>{
            fn.apply(this,arguments) 
             timer=null
                  },delay)
               }
             }
            }
        return {throttle}
}

使用的时候只需要传入提前定好的类fn和所需延迟时间delay即可

猜你喜欢

转载自blog.csdn.net/2301_77456141/article/details/134187390