一文带你实现节流防抖函数

节流和防抖是较为相似的概念,本文先从概念上理解,然后探讨其应用场景,最后实现这两个函数。

节流

1. 概念

用户的方法在某个时间段只执行一次,即每指定时间内最多只调用一个函数。

用一个自身理解的例子来说就是:建造水坝在河道中,我们不能让水不能流动,而是只能让水流动慢一些。

2. 应用场景

  1. 搜索框输入时的实时联想
  2. 监听 scroll 事件计算位置信息

3. 流程图

4. 代码实现

function throttle(func, wait) {
  let lastTime = 0;    // 上一次执行时间
  let time = null;    // 定时器

  return function () {
    if (time) {
      clearTimeout(time);         // 清除定时器
      time = null;
    }

    let self = this;
    let args = arguments;
    let nowTime = +new Date();

    const remainWaitTime = wait - (nowTime - lastTime);     // 剩余等待执行时间

    if (remainWaitTime <= 0) {
      // 更新执行时间,执行函数
      lastTime = nowTime;
      func.apply(self, args);
    } else {
      // 在剩余执行时间过后,更新时间,执行函数,重置定时器
      timer = setTimeout(function () {
        lastTime = +new Date();
        func.apply(self, args);
        timer = null;
      }, remainWaitTime);
    }
  };
}

防抖

1. 概念

在某个事件内的N个动作会被忽略,只有事件后由程序触发的动作是有效的。直白一点的话,就是自最近一次触发后延迟指定时间调用函数。

用一个自身理解的例子就是:我正在抖腿,等到不抖腿了才会行走。

2. 应用场景

  1. input输入框架的格式验证
  2. 提交按钮的点击事件

3. 流程图

4. 代码实现

function debounce(func, wait) {
  let time = null;
  
  return function() {
    if (time) {
      clearTimeout(time);    // 清除定时器
      time = null;
    }
    
    let self = this;
    let args = arguments;
  
    time = setTimeout(function () {
      func.apply(self, args);     // 执行函数
      time = null;
    }, wait);
  }
}

猜你喜欢

转载自juejin.im/post/7126479213360021540