前端项目中,防抖和节流实际上遇到的频率特别的高,因为浏览器的性能是有限的,为了达到性能优化的目的,所以防抖节流的知识还是早点掌握好一点。
function top() {
var top = document.documentElement.scrollTop || document.body.scroolTop
console.log(top)
};
window.onscroll = top
鼠标滚轮轻轻一滚动,会发现事件已经打印了这么多次,这个时候就会发现一个问题,这个函数的默认执行效率太高了,我们完全不用这么浪费浏览器的性能。(执行效率高到按一下键盘的向下方向键就会打印8-9次的地步)
然后我们用防抖函数来优化它
function top() {
let top = document.documentElement.scrollTop
console.log(`滚动条的位置:${top}`)
};
function debounce(fn, wait) {
let timer = null
return function() {
if (timer) {
//如果进入这里,定时器已经在执行了,并且重新触发了这个计时器,那就清除,在重新计时
clearTimeout(timer)
}
timer = setTimeout(fn, wait)
}
}
window.onscroll = debounce(top,1000)