定义
- 防抖:多次触发事件,事件处理函数只执行一次。例如点击事件,我们在延迟时间内连续点击,只会执行一次,停止点击超出延迟时间,然后继续点击才会再次执行。
- 节流:事件触发后,延迟时间内,事件处理函数不能再次被调用。例如点击事件,我们不停的点击,事件会执行多次,但是有时间间隔,间隔时间接近于延迟时间。
实现
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);
}
本文介绍了JavaScript中两种常用的函数优化技巧——防抖(debounce)和节流(throttle),并提供了具体的实现示例。防抖技术确保在特定延迟时间内多次触发事件后只执行一次,而节流则限制了事件处理函数的执行频率,保证在设定的时间间隔内执行。这两个方法常用于优化UI响应,如滚动事件、输入验证等场景。
798

被折叠的 条评论
为什么被折叠?



