防抖debounce、节流throttle

290 阅读1分钟

防抖 debounce

连续点击,停止后,只取最后一次执行

使用场景

  1. 用户在输入框连续输入,停止后,才触发查询
  2. 连续点击按钮,防止重复请求
<button id="btn1">防抖</button>
<script>
  function cyDebounce(fn,time=1000){
    let timer = null
    return function(){
      if(timer){
        clearTimeout(timer) // 只取最后一次操作
      }
      timer = setTimeout(() => {
        fn.apply(this,arguments)
        timer = null
      }, time);
    }
  }

  document.getElementById('btn1').addEventListener('click',cyDebounce(function(){
    console.log('点击了',new Date())
  }))
</script>

节流 throttle

连续拖拽,一段之间内,只取第一次执行

使用场景

  1. 拖拽:直接触发拖拽事件会导致频繁触发,很容易卡顿
<div id="throttle" draggable="true" style="width: 100px;height: 100px;background-color: pink;">节流</div>
<script>
  function cyThrottle(fn,time=1000){
    let timer = null
    return function(){
      if(timer){
        return // 一段时间内,只执行第一次调用,后续的调用直接return
      }
      timer = setTimeout(() => {
        fn.apply(this,arguments)
        timer = null
      }, time);
    }
  }

  document.getElementById('throttle').addEventListener('drag',cyThrottle(function(e){
    console.log('x: ', e.clientX, ' y: ',e.clientY)
  }))