function debounce(func,delay){
let timerId;
return function(...args){
clearTimeout(timerId)
timerId=setTimeout(()=>{
func.apply(this,args)
},delay)
}
}
// 原始函数,可能会频繁触发
function handleInput(value) {
console.log('输入值为:', value);
}
// 使用防抖包装后的函数
const debouncedInput = debounce(handleInput, 300); // 300毫秒的防抖间隔
// 监听输入事件,使用防抖函数
document.querySelector('input').addEventListener('input', (event) => {
debouncedInput(event.target.value);
});
<input />