<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
<style>
body {
height: 5000px;
}
</style>
</head>
<body>
<button id="btn">点击</button>
<br />
<br />
<br />
<br />
<br />
参考文档:https://www.bilibili.com/video/BV1vo4y1y7tD?p=18
<script>
const { log } = console
const scrollFn = function (ev) {
log(3)
}
window.onscroll = myThrottle(scrollFn, 300)
function myThrottle(fn, wait) {
if (typeof fn !== 'function') throw new Error('fn is not an function')
if (typeof wait === 'undefined') wait = 300
let previous = 0
let timer = null
return function (...args) {
let now = new Date()
let self = this
let interval = wait - (now - previous)
if (interval <= 0) {
timer = null
fn.apply(self, args)
previous = new Date()
} else if (!timer){
timer = setTimeout(() => {
timer = null
fn.apply(self, args)
previous = new Date()
}, interval)
}
}
}
</script>
</body>
</html>