
获得徽章 0
赞了这篇沸点
#每天一个知识点#
js 实现防抖和节流函数
1. 防抖函数(Debounce)
function debounce(func, delay) {
let timer;
return function(...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 使用示例
window.addEventListener('resize', debounce(() => {
console.log('Window resized');
}, 500));
2. 节流函数(Throttle)
function throttle(func, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
func.apply(this, args);
lastTime = now;
}
};
}
// 使用示例
window.addEventListener('scroll', throttle(() => {
console.log('Window scrolled');
}, 500));
js 实现防抖和节流函数
1. 防抖函数(Debounce)
function debounce(func, delay) {
let timer;
return function(...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 使用示例
window.addEventListener('resize', debounce(() => {
console.log('Window resized');
}, 500));
2. 节流函数(Throttle)
function throttle(func, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
func.apply(this, args);
lastTime = now;
}
};
}
// 使用示例
window.addEventListener('scroll', throttle(() => {
console.log('Window scrolled');
}, 500));
展开
评论
4
赞了这篇沸点
赞了这篇沸点
赞了这篇沸点
赞了这篇沸点
赞了这篇沸点
赞了这篇沸点