<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
test {
height: 500px;
overflow: auto;
}
.content {
height: 3000px;
}
</style>
</head>
<body>
<div id="test">
<div class="content"></div>
</div>
<script>
// 防抖
// 某一事件被触发后,延迟一定时间执行回调,如果此时间内再次触发此事件,则取消上一次的回调,重新计时规定时间后再触发此回调。
function debonce(cb, time) {
let timer
return function () {
clearTimeout(timer)
timer = setTimeout(function () {
cb()
}, time)
}
}
// 节流 频繁触发的事件规定每多少秒执行一次
function throttle(cb, time) {
let canRun = true
return function () {
if (!canRun) return
canRun = false
setTimeout(function () {
cb()
canRun = true
}, time)
}
}
let fn = () => {
console.log('触发')
}
var test = document.getElementById('test')
test.addEventListener('scroll', debonce(fn, 2000))
// test.addEventListener('scroll', throttle(fn, 2000))
</script>
</body>
</html>