js截流怎么实现
防抖(Debounce)实现
防抖的核心在于延迟执行函数,直到事件停止触发后一段时间才执行。适用于输入框搜索、窗口调整等场景。
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 使用示例
const handleInput = debounce((value) => {
console.log('Searching for:', value);
}, 500);
inputElement.addEventListener('input', (e) => handleInput(e.target.value));
节流(Throttle)实现
节流的核心在于限制函数执行频率,确保在指定时间间隔内只执行一次。适用于滚动事件、鼠标移动等高频触发场景。
function throttle(func, limit) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= limit) {
func.apply(this, args);
lastCall = now;
}
};
}
// 使用示例
const handleScroll = throttle(() => {
console.log('Scrolling...');
}, 200);
window.addEventListener('scroll', handleScroll);
带立即执行选项的防抖
某些场景需要首次触发立即执行,后续触发才防抖。
function debounceImmediate(func, delay, immediate = false) {
let timeoutId;
return function(...args) {
const callNow = immediate && !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
if (!immediate) func.apply(this, args);
timeoutId = null;
}, delay);
if (callNow) func.apply(this, args);
};
}
基于时间戳的节流改进版
更精确控制首次和末次执行的节流实现。
function throttleAdvanced(func, limit) {
let lastTime = 0;
let timeoutId;
return function(...args) {
const now = Date.now();
const remaining = limit - (now - lastTime);
if (remaining <= 0 || remaining > limit) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
lastTime = Date.now();
timeoutId = null;
}, remaining);
}
};
}
Lodash库的现成方案
对于生产环境,推荐使用成熟的工具库实现:

// 防抖
_.debounce(func, 300);
// 节流
_.throttle(func, 300);






