防抖、节流

1.防抖

function debounce(fn, wait) {
    let timer = null; //注意点1:借助闭包
    return function (...args) {
      if (timer) clearTimeout(timer); //注意点2:清除定时器
      timer = setTimeout(() => {
        fn.apply(this, args) //注意点3:setTimout会发生this隐式丢失;改变this指向为调用debounce所指的对象。
      }, wait)
    }
  }



2.节流

function throttle(func, delay) {
  let run = true
  return function () {
    if (!run) {
      return  // 如果开关关闭了,那就直接不执行下边的代码
    }
    run = false // 持续触发的话,run一直是false,就会停在上边的判断那里
    setTimeout(() => {
      func.apply(this, arguments)
      run = true // 定时器到时间之后,会把开关打开,我们的函数就会被执行
    }, delay)
  }
}


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务