防抖与节流
// 防抖函数
function debounce(func, wait, immediate = false) {
let timeout;
return function executedFunction(...args) {
const context = this;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
// 节流函数
function throttle(func, limit) {
let inThrottle;
return function(...args) {
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// 更精确的节流函数(时间戳版本)
function throttleTimestamp(func, limit) {
let lastCall = 0;
return function(...args) {
const context = this;
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(context, args);
}
};
}
// 使用示例
// 防抖示例
const debouncedSearch = debounce((query) => {
console.log('搜索:', query);
}, 300);
// 节流示例
const throttledScroll = throttle(() => {
console.log('滚动处理');
}, 100);
// 测试
// 快速连续调用
for (let i = 0; i < 10; i++) {
setTimeout(() => {
debouncedSearch(`查询${i}`);
throttledScroll();
}, i * 50);
}
核心区别:
防抖(debounce):
- 在事件触发后等待指定时间,如果在此期间再次触发,则重新计时
- 适合:搜索框输入、窗口resize
节流(throttle):
- 在指定时间间隔内只执行一次
- 适合:滚动事件、鼠标移动
两种方法都能有效控制函数执行频率,根据具体场景选择使用。
挣钱养家

浙公网安备 33010602011771号