JS 性能优化:防抖(debounce)、节流(throttle)

一、防抖(debounce)

const title = document.getElementById('title')
// let timer = null
// title.addEventListener('keyup', function () {
//   if(timer) {
//     clearTimeout(timer)
//   }
//   timer = setTimeout(()=>{
//     console.log(title.value)
//     timer = null
//   }, 500)
// })


// 防抖
function debounce(fn, delay = 500) {
  let timer = null
  return function () {
    if(timer)clearTimeout(timer)
    timer = setTimeout(()=>{
      fn.apply(this, arguments)
      timer = null
    }, delay)
  }
}

title.addEventListener('keyup', debounce(function (){
  console.log(this.value)
}, 500))

二、节流(throttle)

const div1 = document.getElementById('div1')
// let timer = null
// div1.addEventListener('drag', function (e) {
//   if(timer)return;
//   timer = setTimeout(()=>{
//     console.log(e.offsetX, e.offsetY)
//     timer = null
//   }, 500)
// })

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

  }
}

div1.addEventListener('drag', throttle(function(e){
  console.log(e.offsetX, e.offsetX)
},200))

猜你喜欢

转载自blog.csdn.net/jal517486222/article/details/105559658