JS之手写防抖节流

109 阅读1分钟

由于之前老是把防抖节流弄混淆,今天发篇文章来记录下,以免后续遗忘。

概念:

  • 防抖:隔一段时间后才触发一次
  • 节流:在触发很多次情况下,让其一段时间后才触发最后那一次

应用场景:

  • 防抖:输入框输入时(input)...
  • 节流:浏览器窗口变化(resize)、页面滚动(scroll)、拖拽(drag)...

手写防抖:

function debounce(fn, delay) {
  let timer = null;  //这里的timer是闭包中的,避免被外部使用
  return function () {
    if(timer) {  //如果有之前的定时器则清空(重新计时)
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)  // apply(函数本身,[传递进来的参数] )
      timer = null;
    }, delay)
  }
}

//使用自己封装的防抖
const input = document.getElementById('input1')
input.addEventListener('keyup', debounce(() => {
    console.log(input.value)
}, 500)) 

//html里的代码
// <input type="text" id="input1">

手写节流:

function throttle(fn, delay = 100) {
    let times = null;
    return function () {
       if (times) {
          return
       }
     times = setTimeout(() => {
       fn.apply(this, arguments)   // apply(函数本身,[传递进来的参数] )
         times = null
       }, delay)
     }
  }

 //使用自己封装的节流
const div1 = document.getElementById('div1')
  div1.addEventListener('drag', throttle((e) => {
  console.log(e.offsetX , e.offsetY);
}))

//html里的代码
//<div id="div1" draggable="true"> </div>

其中参数说明: apply(this,argument)

第一个this:改变this指向

第二个参数argument:用于接收函数里头的参数 。 比如节流函数的e。

注 : 自己学习整理,如果有不对的地方,还请多多指教,谢谢大家 ~!