简单版-手写防抖(debounce)和节流(throttle)

前言

在前端需求开发中,经常需要绑定一些持续触发的事件,例如 scroll事件、onmouseover事件等等,但实际项目中我们并不希望这么频繁的去执行,因为会极大地浪费资源,降低应用性能。

防抖和节流可以减少调用频率,目前是解决上边这个问题比较好的方案。

现有功能介绍

防抖(debounce)

防抖就是指触发事件后在 n 秒后函数只能执行一次,如果在 n 秒内又触发了该事件,则会重新计算函数的执行时间。比如 n=10,如果在第8秒又触发了,则又会从0秒开始计算。

节流(throttle)

节流就是指连续触发事件但是在 n 秒中只执行一次函数,节流是在一段时间内只运行一次。比如 n=10,那一分钟就是执行6次

实现原理

防抖和节流都可以通过 setTimeout函数模拟实现,实现初衷都是要降低回调执行频率
防抖是一定时间连续触发的事件,只在最后一次触发后的第n秒执行一次(只执行一次)。而节流一段时间内只执行一次(会执行多次)。

手写防抖函数

 // 首先,我们先定义一个input
 <input type="text">
// 获取input
let inputDom = document.querySelector("input");
const myDebounceFn = () => {
  console.log(inputDom, "inputDom");
};
/**
 * 
 * @params:
 *    fn: 回调函数
 *    time: 延迟时间
 *  
 * */
const myDebounce = (fn, time) => {
  let timer = null;
  return () => { 
    if (timer) { // 有就清除,没有就加定时器
      clearTimeout(timer);
    }
    timer = setTimeout(fn, time);
  };
};
// 绑定input事件,调用myDebounce方法
inputDom.addEventListener("input", myDebounce(myDebounceFn, 2000));

手写节流函数

 // 首先,我们先定义一个box
<div class="box">
  <div class="a"></div>
  <div class="a"></div>
</div>
let box = document.querySelector(".box");
const myThrottlingFn = () => {
  console.log(box, "box");
};
// 节流函数 一定时间内 多个事件合成一个
// 1、提交表单 2、高频监听事件
/**
 * 
 * @params:
 *    fn: 回调函数
 *    wait: 延迟时间
 *  
 * */
const myThrottling = (fn, wait) => {
  let timer = null;
  return () => {
    if (!timer) {
      timer = setTimeout(() => {
        fn(); // 执行回调
        timer = null;
      }, wait);
    }
  };
};
box.addEventListener("touchmove", myThrottling(myThrottlingFn, 2000));
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

404not~found

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值