函数节流throttle和函数防抖debounce
作用:减少单位时间内函数调用的次数,让性能更好
应用:
节流:滚轮、mousemove事件等
防抖:输入框
实现:利用时间戳来实现单位时间内只触发第一次函数调用
节流:
function throttle(fn, wait) {
// 记录上一次调用函数的时间
let lastTime = 0;
return function throttled() {
// 当前将要调用函数的时间
const nowTime = Date.now();
if (nowTime - lastTime < wait) return;
// 调用函数
fn.apply(this, arguments); // this --> document
// 同步时间戳
lastTime = nowTime;
}
}
function scroll() {
}
document.onscroll = throttle(scroll, 200);
防抖:
function debounce(fn, wait) {
let timer = null;
return function debounced() {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, wait)
}
}