节流函数和防抖函数

118 阅读1分钟
//防抖函数
function debounce(func,delay){
  let timer = null
   return ()=>{
        if(timer)clearTimeout(timer)
           timer = setTimeout(()=>{
                       func
                        },delay)
                     }
  }
//防抖函数优化(通用)
function debounce(func,delay){
     let timer = null
     return(...arg)=>{
         if(timer)clearTimeout(timer)
            timer = setTimeout(()=>{
                 func.apply(this,arg)
                       },delay)
              }
    }
//节流函数
function throttle(fne,intervar){
let last = 0
return (...arg)=>{
let now = new Date().getTime();
if(now-last > intervar){
fne.apply(this,arg)
last = now
}
}
}
//节流函数优化(通用版本)
function throttle(fn, wait) {
  let timer = undefined;
  let lastCallTime = Date.now();
  return function() {
    const timeSinceLastCall = Date.now() - lastCallTime;
    const shouldCall = timeSinceLastCall >= wait;
    if (shouldCall) {
      const args = arguments; 
      timer = setTimeout((fn.apply(this, args), (timer = undefined)), wait);  
      lastCallTime = Date.now();
    }
  };
}

使用方法:
      事件一般是滚动,搜索框,点击      时间则是限制多少秒后能点击   1秒=1000
throttle(事件,时间)