JavaScript性能优化利器:全面解析防抖(Debounce)与节流(Throttle)技术、应用场景及Lodash、RxJS、vueuse/core Hook等高效第三方库实践攻略
warning:
这篇文章距离上次修改已过267天,其中的内容可能已经有所变动。
// 防抖函数
function debounce(fn, wait) {
let timeout = null;
return function() {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) fn.apply(context, args);
};
}
// 节流函数
function throttle(fn, wait) {
let previous = 0;
return function() {
let context = this;
let args = arguments;
let now = new Date();
if (now - previous > wait) {
fn.apply(context, args);
previous = now;
}
};
}
// 使用场景示例
// 防抖应用于搜索框输入
let searchBox = document.getElementById('search-box');
let debouncedInput = debounce(search, 500);
searchBox.addEventListener('input', debouncedInput);
// 节流应用于鼠标移动
let mouseMove = throttle(handleMouseMove, 1000);
document.addEventListener('mousemove', mouseMove);
这段代码展示了如何使用防抖和节流函数来优化事件处理。防抖确保事件处理器在 n 秒内不会被频繁触发,而节流则限制了一定时间内事件处理器的调用频率。这两种技术在输入字段的实时验证、滚动事件的处理和高频率触发的按钮点击等场景中有着广泛的应用。
评论已关闭