JS中函数的防抖(debounce)与节流(throttle)

在实际的用户交互过程中,无论是PC还是移动端,都会避免不了会用到防抖和节流来做相应的优化。

常见使用场景:

  • 窗口resize,scroll,以及输入框中搜索请求数据等。

概念:

  • 防抖:debounce。其概念就是去抖动,基本思路:将多次动作合并为一次动作执行。

  • 节流:throttle。其概念就是减少动作的执行次数,基本思路:不能让用户的方法都不执行,而是在一定时间段内减少执行的次数,如果都不执行,就是debounce了。

防抖:

  • 使用场景:input框的输入验证,用户连续点击提交等,防止用户的连续疯狂输入/点击按钮,导致短时间内多次访问服务器,压力过大、交互变卡。

  • 实现思路:将目标动作放在一个setTimeout中,这个目标动作是一个事件的回调函数,如果这个回调在连续被调用,那么通过clearTimeout,这些次动作就都不被执行,直至最后一次触发回调函数,再执行。

  • 代码:

    const debounce = (fn, delay) => {
      let timer = null;
      return (e) => {
        console.log('clear timer if function re-call, until the last call');
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          console.log('call the fn')
          fn();
        }, delay)
      }
    }
    
    const func = debounce(() => {
      console.log('some actions');
    }, 500)

节流:

  • 使用场景:节流会用在比input框、click、keyup等事件,触发更频繁的场景下。例如:resize、scroll、touchmove、mousemove等事件下,由于此类事件触发更加频繁,所以使用节流来控制执行的频率。

  • 实现思路:若想让用户的方法在特定时间段内只执行一次,我们需要保存上次执行的时间点与定时器。

  • 代码:

const throttle = (fn, threshHold = 150) => {
  let timer = null;
  let start = new Date();
  return () => {
    let now = new Date() - 0;
    if (timer) {
      clearTimeout(timer);
    }

    if (now - start >= threshHold) {
      console.log('now', now, now - start); // about 150
      fn();
      start = now;
    } else {
      // call the fn() when out of the evts.
      timer = setTimeout(() => {
        fn();
      }, threshHold)
    }
  }
}

const mounsemove = throttle((e) => {
  console.log(e.pageX, e.pageY);
}, 200)