节流和防抖

97 阅读1分钟
节流

n秒内只运行一次,若在 n 秒内重复触发,只有一次生效

  1. 时间戳方式
function throttle(fn, interval=300) {
    let oldTime = Date.now()
    return function(..args){
        let newTime = Date.now()
        if(newTime - oldTime >= interval){
            fn.apply(this, args)
            oldTime = newTime
        }
    }
}
  1. setTimeout 方式
function throttle2(fn, interval){
    let timer
    return function(...args){
        if(!timer){
            timer = setTimeout(()=>{
              fn.apply(this, args)
              timer = null
            }, interval)
        }    
    }
}
防抖

n 秒后触发,若在 n 秒内触发,重新计时

function debounce(fn, delay){
  let timer
  return function(){
      const context = this
      const args = arguments
      if(timer){clearTimeout(timer)}
      timer = setTimeout(function(){
          fn.apply(context, args)
      }, delay)
      
  }
}
  1. 防抖如果需要立即执行

function debounce(fn, delay, immediate){
    let timer
    return function(){
        const context = this
        const args = arguments
        if(timer){clearTimeout(timer)}
        if(immediate){
            let callNow = !timer
            
            // n 秒后触发,重新计时
            timer = setTimeout(function(){
                    timer = null
            }, delay)
            if(callNow){fn.apply(context, args)}
        } else {
            timer = setTimeout(function(){
                fn.apply(context, args)
            }, delay)
        }
    }
}

应用场景
节流
  1. 滚动加载,scroll
防抖
  1. 搜索框搜索输入。只需用户输入完,再发送请求
  2. 窗口大小 resize