作为一名还没怎么入门的小白,节流和防抖是我望而生畏的两种算法。
但是,现在将鼓起勇气,为大家分享最简单的节流和防抖(最基础版的),等我会了更多,再来更新。
防抖(debounce)
我觉得这节流和防抖这两个词语就能把人吓死,因为完全不知道什么叫防抖和节流。因此,首先,我们需要掌握它们的含义。
防抖含义:事件被触发后延迟n秒再执行回调,如果在这n秒内又被触发,则重新计时。
举个例子:
当用户拖动页面滚动条后,会触发某些事件。此时,我们仅仅将页面滚动的高度打印出来。实际中,当然要进行某些复杂的操作。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
html {
height: 500vh;
}
</style>
</head>
<body>
<script>
window.addEventListener('scroll', () => {
const scrollResult = window.scrollY || document.documentElement.scrollTop;
console.log('页面已滚动高度为',scrollResult);
})
</script>
</body>
</html>
我们会发现浏览器在监听到页面滚动后再不断打印出数据,但如果说当页面滚动后,需要进行执行比较复杂的函数,而不是简单的打印,频繁的执行函数,必将带来性能的浪费。
因此,可以当用户停止滚动页面n秒后再执行函数,如果在这n秒内,用户又进行了滚动,则重新开始计时。
法一:
const scrollEvent = ()=>{
const scrollResult = window.scrollY || document.documentElement.scrollTop;
console.log('页面已滚动高度为',scrollResult);
}
let timer = null;
function debounce(fn,delay){
//如果timer存在的情况下就清除延时器。作用是:只要用户一滚动,则清除此时的延时器,然后再来一个全新的延时器
// 假设我们的等待时间为1s,在这1s期间,如果用户滚动了,则重新计时再等1s
timer&&clearTimeout(timer);
timer = setTimeout(fn,delay); // 记得这里要将延时器的id赋值给timer,方便之后清除定时器
}
window.addEventListener('scroll', ()=>{
debounce(scrollEvent,1000);
})
完美的工作了,如果要求不高,这就应该解决了问题。
法二:
但是,此时的timer成了全局变量,容易造成变量混淆。因此,我们可以使用闭包,将其隐藏起来。
const scrollEvent = () => {
const scrollResult = window.scrollY || document.documentElement.scrollTop;
console.log('页面已滚动高度为', scrollResult);
}
function debounce(fn, delay) {
let timer = null; // ② 对,说的就是你,亲爱的上级作用域
return () => {
// ①这里的timer会向上级作用域寻找它的值 (即②处)
timer && clearTimeout(timer);
timer = setTimeout(fn, delay); //同样fn,delay的值也可以在上级作用域找到
}
}
const debounceScroll = debounce(scrollEvent,1000);
//因为上面的debounce的返回值是一个函数,因此debounceScroll是一个函数
window.addEventListener('scroll', debounceScroll); //这里的写法是不是比法一清爽太多了
节流 (throttle)
节流就是每过n秒仅执行一次回调函数。如单位时间内多次触发函数,也只有一次生效。
节流的写法同样也有很多,这里我当然就写最简单的方法。
法一:
function printTime(){
console.log(new Date().getSeconds()); //打印当前时间的秒数
}
let timer = null;
const scrollEvent = (delay) => {
if (!timer) {
// 如果延时器不存在的话,则新开一个延时器,重新等待1s
timer = setTimeout(() => {
printTime();
timer = null; //执行完函数后,将timer设置为null
}, delay);
}
}
window.addEventListener('scroll', ()=>{
scrollEvent(1000);
});
无论我怎么滚动,1s内它就只会打印一次。
同样这些写的弊端也显而易见,timer暴露成了全局变量。
因此和之前一样,我们用闭包写法来实现。
function printTime() {
console.log(new Date().getSeconds()); //打印当前时间的秒数
}
function throttle(fn, delay) {
let timer = null;
return () => {
if (!timer) {
// timer如果不存在则执行下面的代码,给他添加一个timer
timer = setTimeout(() => {
console.log(new Date().getSeconds());
timer = null; // 重新将timer设置为null
}, delay);
}
}
}
const scrollEvent = throttle(printTime, 1000);
window.addEventListener('scroll', scrollEvent);