JS 手写防抖和节流

本文深入探讨了JavaScript中的防抖(debounce)和节流(throttle)技术,这两种技术常用于优化事件处理,特别是对于高频触发的场景如搜索框输入和表单验证。防抖确保在特定时间段内只执行最后一次触发的回调,而节流则保证在单位时间内只执行一次回调。通过示例代码展示了如何实现防抖和节流,并推荐使用Lodash库来简化这一过程。了解并合理运用这些技术可以显著提升用户体验和性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

防抖

原理:

防抖(debounce):在时间 n 秒内多次触发事件,则 以最后一次触发开始, n 秒后才会执行事件的回调函数。

应用场景:

搜索框,输入后1000毫秒搜索

debounce(fetchSelectData, 300);

表单验证,输入1000毫秒后验证

debounce(validator, 1000);

实现防抖:

let input = document.getElementsByTagName("input")[0];

let getUserAction = () => {
  console.log(new Date());
};

function debounce(func, time) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, time);
  };
}

input.addEventListener("keyup", debounce(getUserAction, 1000));

想让回调函数立即执行一次

function debounce(func, time, flag) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    // flag 标志是否立即执行。
    // 当timer为null时表示函数是第一次执行,我们立即执行一次它。
    if (flag && !timer) {
      func.apply(this, args);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, time);
  };
}

节流

定义:

节流(throttle):在单位时间内只执行一次回调函数,而在单位时间内多次触发还是只能执行一次。

实现:

1. 时间戳方式实现:

第一次触发事件,回调函数执行,而最后一次不会执行。

function throttle(func, time) {
  let pre = 0;
  return function (...args) {
    if (Date.now() - pre > time) {
      pre = Date.now();
      func.apply(this, args);
    }
  };
}
2. 定时器方式实现:

第一次触发事件回调函数不执行,而最后一次执行。

function throttle(func, time) {
  let timer = null;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        func.apply(this, args);
      }, time);
    }
  };
}


项目使用 Lodash 库 更加方便

debounce

具体查看官网 https://lodash.com/docs/4.17.15#debounce

let debounced = _.debounce(func, [wait=0], [options={}])
debounced()

参数:
func (Function) : 去抖动的函数。
[wait=0] (number) : 延迟的毫秒数。
[options={}] (Object) : 选项对象。

返回值:
(Function) : 返回新的去抖动函数。

throttle

具体查看官网 https://lodash.com/docs/4.17.15#throttle

let throttled =  _.throttle(func, [wait=0], [options={}])
throttled()

参数:
func (Function) : 要节流的函数。
[wait=0] (number) : 限制调用的毫秒数。
[options={}] (Object) : 选项对象。

返回值:
(Function) : 返回新的节流函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欢莱

为您解决问题,此项目我成功完成

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值