<!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>Document</title>
<style>
div {
width: 200px;
height: 20000px;
background-color: aquamarine;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div>
高度20000px
</div>
<script>
function debounce(fn, wait) {
let timeout = null; //定义一个定时器
console.log(timeout);
return function() {
if (timeout !== null)
clearTimeout(timeout); //清除这个定时器
timeout = setTimeout(fn, wait);
}
}
// 处理函数
function handle() {
console.log(Math.random());
}
// 滚动事件1
window.addEventListener('scroll', debounce(handle, 1000));
// 滚动事件2
// window.addEventListener('scroll', a1);
// function a1() {
// let timeout = null; //定义一个定时器
// console.log(timeout);
// }
</script>
</body>
</html>
debounce()中的 "console.log(timeout);" 不应该是每次滚动都触发一次吗? 但实际情况是只会触发一次,我没看懂这里的逻辑关系,辛苦看懂的帮忙解释一下。