5

防抖和节流的区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行

防抖-定时器实现版

// 防抖 - 定时器
function debounce(fn, wait) {
  var timer = null
  return function() {
    var context = this
    var args = arguments
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn.bind(context, args), wait)
  }
}

防抖-定时器参数版实现版

// 防抖-参数版
function debounce(fn, wait) {
  var timer = null
  return function() {
    var context = this
    var args = arguments
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => { fn.apply(this, args) }, wait)
  }
}

节流 - 时间戳实现版

// 节流 - 时间戳
function throttle(fn, wait) {
  var prev = Date.now()
  return function() {
    var now = Date.now()
    if (now - prev > wait) {
      fn()
      prev = Date.now() 
    }
  }
}

节流 - 时间戳实现版

// 节流 - 定时器
function throttle(fn, wait) {
  var timer = null
  return function() {
    if (!timer) {
      timer = setTimeout(() => {
        timer = null
        fn()
      }, wait)
    }
  }
}

示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖、节流</title>
</head>
<body>
  <input type="text" id="input">
  <button id="button">提交</button>
</body>
</html>

<script>

  // 防抖 - 定时器
  function debounce(fn, wait) {
    var timer = null
    return function() {
      if(timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(fn.bind(this, this.value), wait)
    }
  }
  function checked(value) {
    console.log(value)
  }
  document.getElementById('input').addEventListener('input', debounce(checked, 1000))
 // 防抖-参数版
 //  function debounce(fn, wait) {
 //   var timer = null
 //   return function() {
 //     var context = this
 //     var args = arguments
 //     if(timer) {
 //       clearTimeout(timer)
 //     }
 //     timer = setTimeout(() => { fn.apply(this, args) }, wait)
 //   }
 // }

  // 节流 - 时间戳
  // function throttle(fn, wait) {
  //   var prev = Date.now()
  //   return function() {
  //     var now = Date.now()
  //     if (now - prev > wait) {
  //       fn()
  //       prev = Date.now() 
  //     }
  //   }
  // }
  
  // 节流 - 定时器
  function throttle(fn, wait) {
    var timer = null
    return function() {
      if (!timer) {
        timer = setTimeout(() => {
          timer = null
          fn()
        }, wait)
      }
    }
  }
  function btnClick() {
    console.log('submit')
  }
  document.getElementById('button').addEventListener('click', throttle(btnClick, 1000))
</script>

参考
https://www.jianshu.com/p/c8b86b09daf0
https://www.cnblogs.com/youma/p/10559331.html


记得要微笑
1.9k 声望4.5k 粉丝

知不足而奋进,望远山而前行,卯足劲,不减热爱。


« 上一篇
类型转化