防抖和节流

定义

  • 防抖:多次触发事件,事件处理函数只执行一次。例如点击事件,我们在延迟时间内连续点击,只会执行一次,停止点击超出延迟时间,然后继续点击才会再次执行。
  • 节流:事件触发后,延迟时间内,事件处理函数不能再次被调用。例如点击事件,我们不停的点击,事件会执行多次,但是有时间间隔,间隔时间接近于延迟时间。

实现

1.防抖

function debounce(fn, delay, immediate, ...outerArgs) {
  let timer = null;
  return function (...innerArgs) {
    if (timer) clearTimeout(timer);
    if (immediate) {
      let callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, delay);
      if (callNow) fn.call(this, ...outerArgs, ...innerArgs);
    } else {
      timer = setTimeout(() => {
        fn.call(this, ...outerArgs, ...innerArgs);
      }, delay)
    }
  };
}

2.节流

function throttle(fn, delay, immediate, ...outerArgs) {
  let lastTime = 0;
  let timer = null;
  return function (...innerArgs) {
    if (immediate) {
      let nowTime = Date.now();
      if (nowTime - lastTime > delay) {
        lastTime = nowTime;
        fn.call(this, ...outerArgs, ...innerArgs);
      }
    } else {
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          fn.call(this, ...outerArgs, ...innerArgs);
        }, delay)
      }
    }
  };
}

immediate:是否立即执行。

outerArgs和innerArgs都写,是为了更好的接受参数,可以在创建回调函数时传入参数,也可以在执行回调函数传入参数。

使用

html部分

<button onclick="handleClick('张三')">点击</button>

javascript部分

const clickDebounce = debounce(print, 2000, false);
const clickThrottle = throttle(print, 2000, false);

function handleClick(params) {
  clickDebounce(params);
  clickThrottle(params);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值