<!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>
body {
height: 4000px;
}
</style>
</head>
<body>
<!-- 防抖 -->
<script>
function showScrollTop() {
var scrollTop = document.documentElement.scrollTop;
console.log(scrollTop);
}
function debounce(fn, delay) {
var timer = null;
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, delay);
}
}
window.addEventListener('scroll', debounce(showScrollTop, 300));
</script>
</body>
</html>
闭包我是理解的,可是这个函数为什么不是从var timer=null开始执行?