性能优化这个领域的很多内容都很碎片化,比如对图片方面的优化(计算图片的大小、图片加载优化)懒加载,包括今天要总结的防抖和节流。就算你没听过防抖节流,但是你做项目的时候,一定遇到过。如果你知道了这块知识,那么你之前的问题就迎刃而解了。
防抖:多次触发事件该事件只能被执行一次,指定时间过后可再次执行,本质上就是以最后的操作为标准在指定时间内
function debounce(fn) {
let time = null;
return function () {
//清除前一个定时器
clearTimeout(time);
//创建新的定时器,使用apply修复this指向
time = setTimeout(() => {
a.apply(this, arguments)
}, 1000)
}
}
function a() {
let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
console.log('top-->',scrollTop)
}
window.onscroll = debounce(a)
节流:在指定时间内,只能触发一次事件,该时间过后可再次触发事件。
function throttle(fn) {
//记录是否在时间内
let time = true;
return function () {
if(!time) {
return ;
}
time = false;
setTimeout(() => {
fn.apply(this,arguments);
// 在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循 环了。当定时器没有执行的时候标记永远是false,在开头被return掉
time = true;
},1000)
}
}
function a() {
let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
console.log('top-->',scrollTop)
}
window.onscroll = throttle(a)