封装防抖节流函数

关于防抖和节流的函数我就不一一展开讲了,下面主要写一下防抖和节流函数的封装:

 

防抖

function debounce(fn, delay = 500) {
  // timer是闭包中的
  let timer = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null
    }, delay)
  }
}

节流

function throttle(fn, delay = 100) {
  let timer = null
  return function () {
    if (timer) {
      return
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null
    }, delay)
  }
}

 

例子:

//防抖
const input1 = document.getElementById("input1")

input1.addEventListener("keyup", debounce(() => {
  console.log(input1.value)
}), 600)


//节流
const div1 = document.getElementById("div1")

div1.addEventListener("drag", function (e) {
  console.log(e.offsetX, e.offsetY)
}, 200)

 

你可能感兴趣的:(Web前端)