实现节流去抖函数,初中级前端面试必考知识点

本文详细介绍了前端面试中常考的节流和去抖技术,包括基本概念、应用场景和代码实现。节流用于限制函数在特定时间内的调用频率,如搜索联想、滚动事件处理。而去抖则确保在最后一次操作后等待指定时间再执行,适用于用户名检测、窗口尺寸计算等场景。
摘要由CSDN通过智能技术生成

完整高频题库仓库地址: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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值