//防抖
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 使用示例
function handleInput() {
console.log('Input event debounced');
}
const debouncedHandleInput = debounce(handleInput, 300);
//节流
function throttle(func, delay) {
let lastExecuted = 0;
return function(...args) {
const now = Date.now();
if (now - lastExecuted >= delay) {
func.apply(this, args);
lastExecuted = now;
}
};
}
// 使用示例
function handleScroll() {
console.log('Scroll event throttled');
}
const throttledHandleScroll = throttle(handleScroll, 300);
javascript 手写防抖节流函数
于 2024-04-19 15:29:29 首次发布