节流
固定时间间隔只执行一次
const throttle = (fn, wait) => {
console.log('throttle start.....')
let lastTime = 0;
return (...args) => {
console.log('scroll执行内部');
console.log(args);
let now = new Date();
if(now - lastTime > wait){
lastTime = now;
fn.apply(this, args);
console.log('this?????');
console.log(this);
}
}
}
window.onscroll = throttle(() => {
console.log('节流执行滚动。。。。。');
}, 500);
防抖
在第一次触发事件时,不立即执行函数,而是给出一个期限值比如200ms,
在这之内无新触发事件就立即执行,否则重新计时
const debounce = (fn, wait) => {
console.log('debounce start');
let timer = 0;
return (...args) => {
console.log('debounce scroll enter');
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, wait);
}
}
window.onscroll = debounce(() => {
console.log('防抖触发滚动');
}, 500)
防抖: 两次事件触发时间间隔等于指定时间才执行一次
节流: 上一次事件触发执行后,指定时间段内不再执行,之后的事件触发才执行
区别: 防抖在指定时间段内如有事件触发,会重新计时,而节流不会。
应用场景:
实时搜索 - 节流
页面缩放 - 防抖
网友评论