防抖和节流

111 阅读1分钟

防抖和节流

防抖:
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。简单来说就是王者回城被打断,想回城需要重新走进度条。
function debounce(fn, delay = 200) {
  let timer = 0
  return function() {
    // 如果这个函数已经被触发了
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments); // 透传 this和参数
      timer = 0
    },delay)
  }
}
节流:
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数,简单来说就是王者技能的CDCD时间到了才能进行下一次技能的释放。
function throttle(fn, delay = 200) {
  let  timer = 0
  return function () {
    if(timer){
      return
    }
    timer = setTimeout(() =>{
      fn.apply(this, arguments); // 透传 this和参数
      timer = 0
    },delay)
  }
}

也可以用lodash中的防抖和节流方法来实现。_.debounce(func, [wait=0], [options=])_.throttle(func, [wait=0], [options=])