关于javascript:实现节流去抖函数

25次阅读

共计 868 个字符,预计需要花费 3 分钟才能阅读完成。

残缺高频题库仓库地址:https://github.com/hzfe/awesome-interview

残缺高频题库浏览地址:https://febook.hzfe.org/

节流

1. 基本概念

throttle(func, wait)

每 wait 毫秒内最多只调用一次 func。

2. 利用场景

  • 搜寻框输出时的实时联想。
  • 监听 scroll 事件计算地位信息。

3. 流程图

4. 编写代码

function throttle(func, wait) {
  let lastTime = 0;
  let timer = null;

  return function () {if (timer) {clearTimeout(timer);
      timer = 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. 基本概念

debounce(func, wait)

自最近一次触发后提早 wait 毫秒调用 func。

2. 利用场景

  • 注册时输出完用户名后检测是否被占用。
  • 监听 resize 事件计算尺寸信息。

3. 流程图

4. 编写代码

function debounce(func, wait) {
  let timer = null;

  return function () {if (timer) {clearTimeout(timer);
      timer = null;
    }

    let self = this;
    let args = arguments;

    timer = setTimeout(function () {func.apply(self, args);
      timer = null;
    }, wait);
  };
}

正文完
 0