JS 手写防抖和节流

防抖

原理:

防抖(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) : 返回新的节流函数。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

欢莱

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

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

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

打赏作者

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

抵扣说明:

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

余额充值