通用函数:
function throttle(callback, wait) {
let start = 0
return function(e) {
const now = Date.now()
if (now - start >= wait) {
callback.call(this, e)
start = now
}
}
}
function debounce(callback, wait) {
let timer = null
return function(e) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(()=> {
callback(e)
timer = null
}, wait)
}
}
使用方法:
<script>
window.addEventListener('scroll', throttle(function(e) {
console.log(e)
}, 1000))
window.addEventListener('scroll', debounce(function(e) {
console.log(e)
}, 1000))
</script>