手写函数防抖和函数节流

throttle, debounce

函数节流

  • 原理:规定在一个单位时间内,只能触发一次函数。如果这个单位时间内多次触发函数,只有一次生效。
  • 适用场景:
    • 拖拽场景:固定时间内只执行一次,防止超高频次触发位置变动
    • 缩放场景:监控浏览器 resize
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function throttle(fn, delay) {
let canUse = true;
return function () {
if (canUse) {
fn.apply(this, arguments);
canUse = false;
setTimeout(() => (canUse = true), delay);
}
};
}

const throttled = throttle(() => console.log("hi"), 3000);
throttled();
throttled(); //3s内第二次不执行

函数防抖

  • 原理:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,择重新计时。
  • 适用场景:
    • 按钮提交场景:防止多次提交按钮,只执行最后一次
    • 搜索框联想场景:防止联想发送请求,只发送最后一次输入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function debounce(fn, delay) {
let timerId = null;
return function () {
const context = this;
if (timerId) {
window.clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn.apply(context, arguments);
timerId = null;
}, delay);
};
}
const debounced = debounce(() => console.log("hi"), 3000);
debounced(); //3s内调用了第二次,第一次不执行
debounced();