blog

Preview

2020.03.19

不管是防抖(debounce)还是节流(throtting),本质上都是为了解决由于某个事件触发频率太快导致响应速度跟不上的问题,只是表现上存在各自的特点

debounce

防抖又可以叫做去抖动,主要逻辑为对于事件的触发不马上立即执行响应函数,进行一段延时周期,如果延时期间又有新的触发,那么针对于新的触发发起新的一段延时,直到顺利度过延时周期执行响应。

最为常见的例子就是针对于 input 输入内容做校验逻辑,但是输入的速度过快导致校验逻辑频繁触发,这个时候加入防抖可以在输入停止一段时间后触发,避免反复校验。

Realization

function debounce (handler, delay) {
  let timerId;
  return function (...args) {
    timerId = clearTimeout(timerId);
    timerId = setTimeout(() => {
      handler.apply(this, args);
    }, delay);
  }
}

Example

// 创建一个防抖的check函数
const check = debounce(function (inputValue) {
  console.log('check', inputValue);
}, 1000);

check('first');
check('second');
setTimeout(() => {
  check('third after 1500ms');
}, 1500);
// check second
// check third after 1500ms

throttling

节流和防抖类似,都是为了限制短时间内的触发频率,不过与防抖不同的是触发的时间点为一段时间开始的时候,再触发响应后的一段时间内忽略后续触发的响应。

最形象的例子就是鼠标的 click 事件,我只需要第一次点击触发事件,第一次点击后的频繁点击我不希望触发,避免反复触发。

Realization

function throttling (handler, wait) {
  let timerId;
  return function (...args) {
    if (timerId) {
      return;
    }
    handler.apply(this, args);
    timerId = setTimeout(() => {
      timerId = undefined;
    }, wait);
  }
}

Example

// 创建一个节流的click函数
const click = throttling(function (text) {
  console.log('click', text);
}, 1000);

click('first');
click('second');
setTimeout(() => {
  click('third after 1500ms');
}, 1500);
// click first
// click third after 1500ms

Summary

相同点:

不同点: