防抖和节流

105 阅读1分钟

防抖(debounce)

所谓防抖,就是指触发事件在n秒内只执行一次函数,如果在n秒内又执行了一次函数,则会重新计算函数执行时间

function debounce(func,delay){
  let timer=null

  return function (...args){
  
    if(timer) clearTimeout(timer)
    
    timer=setTimeout(()=>{
      func.apply(this,args)
    },delay)
  }

}

节流(throttle)

所谓节流,就是指连续触发事件但是在n秒中只执行一次函数

function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}