获得徽章 2
赞了这篇沸点
图解扫码登录全过程原理 #每天一个知识点#
Rjdeng于2024-08-06 15:25发布的图片
2
#每天一个知识点#
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));
展开
评论
前端开发工程师
前端开发工程师
前端开发工程师
前端开发工程师
前端开发工程师
前端开发工程师
下一页
个人成就
文章被点赞 6
文章被阅读 10,187
掘力值 173
收藏集
1
关注标签
10
加入于