防抖函数的作用是在一定时间内只执行一次函数,常用于优化用户输入、滚动事件等频繁触发的操作。
以下是一个简单的防抖函数实现:
function debounce(func, delay) {
let timerId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
使用方法
function doSomething() {
console.log('Doing something...');
}
const debouncedDoSomething = debounce(doSomething, 1000);
// 在一秒内多次调用 debouncedDoSomething,只有最后一次会执行
debouncedDoSomething();
debouncedDoSomething();
debouncedDoSomething();