防抖(Debounce)
定义:防抖是指在事件被触发后n秒内函数只能执行一次,如果在这n秒内又被重新触发,则重新计算执行时间。
用途:用于限制某个函数在短时间内只执行一次,比如用户连续点击按钮时,只触发一次事件处理函数。
代码示例(使用JavaScript):
function debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
const myEfficientFn = debounce(function() {
// 需要防抖的函数体
}, 250);
window.addEventListener('resize', myEfficientFn);
节流(Throttle)
定义:节流是指连续触发事件但是在n秒中只执行一次函数。节流会稀释函数的执行频率。
用途:用于限制某个函数在一定时间内执行的次数,比如滚动加载时,限制滚动事件的触发频率。
代码示例(使用JavaScript):
javascript复制代码
function throttle(func, limit) {
let inThrottle;
return function() {
const context = this;
const args = arguments;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const myEfficientFn = throttle(function() {
// 需要节流的函数体
}, 250);
window.addEventListener('scroll', myEfficientFn);