1. 防抖函数
防抖函数(Debounce Function)用于处理频繁触发的事件,确保在事件触发后的一段特定时间内,如果再次触发则重新计时,只有在这段时间内没有再次触发时,才真正执行相应的函数。
以下是一个简单的防抖函数的实现示例:
function debounce(func, delay = 1000) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 使用示例
function handleMove(event) {
console.log(`鼠标 X 坐标: ${event.clientX}, 鼠标 Y 坐标: ${event.clientY}`);
}
document.addEventListener("mousemove", debounce(handleMove));
2. 节流函数
节流函数(Throttle Function)用于限制函数在一段时间内的执行频率。
以下是一个简单的节流函数的实现示例:
function throttle(func, delay = 1000) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
function printMessage() {
console.log("节流函数执行");
}
window.addEventListener("click", throttle(printMessage));