前端面试问题(十三)
最编程
2024-10-14 12:31:43
...
function debounce(fn, delay) {
let timer;
return function (...args) {
if (timer) clearTimeout(timer); // 如果有定时器,先清除它
timer = setTimeout(() => {
fn.apply(this, args); // 延迟执行目标函数
}, delay);
};
}
// 使用示例
const handleResize = debounce(() => {
console.log('窗口大小改变');
}, 500);
window.addEventListener('resize', handleResize);