简单版-手写防抖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));