17:03分讲解的这个方法好像有问题:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>浏览器页面滚动防抖</title>
<style>
#container {
height: 5000px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container">
</div>
<script>
// 防抖函数
function deBounce(func, wait) {
//使用局部变量保存timer (不污染全局变量)
var timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func, wait);
}
}
// 获取页面滚动高度
function getScrollTop() {
//获取滚动元素
let scrollTop = document.documentElement.scrollTop;
console.log(scrollTop);
}
//错误写法 滚动事件触发一次,就生成一个新的防抖函数
window.onscroll = function () {
var result= deBounce(getScrollTop, 1000)();
};
//正确写法 只在绑定事件时创建一次防抖函数
// 滚动事件触发时,调用的始终是同一个防抖函数实例
// window.onscroll = deBounce(getScrollTop, 1000);
</script>
</body>
</html>