防抖/节流

防抖

防抖是,用户频繁触发事件(如:oninput/onscroll),但是只要最后一次,等用户输入完 / 滚完,就只执行最后一次
初稿

let timer = null
input.oninput = function() {
  if(timer !== null) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    //  do something
  }, 500)
}

改进

但这个代码定义了全局变量,不好,故做下面修改
function debounce(func, delay) {
  let timer = null
  return function a() {
    if(timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func()
    }, delay)
  }
}

input.oninput = debounce(function() {
   // do something     但这种情况下,这里的this就不是input节点了,这是匿名函数做实参,this指的是window,所以还要做一下修改
}, 500)

结果

function debounce(func, delay) {
  let timer = null
  return function a() {
    if(timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func().call(this)      //这回妥了,箭头函数被定义在timer下,timer的父层级debounce的this指的是input,所以这里call this就是input
    }, delay)
  }
}

节流

事件频繁触发,那我就让它多少秒触发一次,定时触发;
与防抖的区别,防抖只要最后一次,节流是定时触发多次;
都是为了防止触发过于频繁

function throttle(fn, delay) {
  let flag = true
  return function() {
    if(flag) {
      setTimeout(() => {
        fn().call(this)
        flag = true
      }, delay)
    }
    flag = false
  }
}

window.onscroll = throttle(function() {
    // do something
}, 500)

posted on 2022-06-22 22:16  In-6026  阅读(26)  评论(0编辑  收藏  举报

导航