防抖:在一定时间内连续触发的,只让最后一次执行
防抖封装:
<body style="height:2400px">
</body>
<script>
function preventJitter(fn, time) {
let timeout = null
let arg = Array.from(arguments)
arg.splice(0, 2)
return function () {
let _this = this
clearTimeout(timeout)
timeout = setTimeout(function () {
console.log(arg);
fn.apply(_this, arg)
}, time)
}
}
function scrollHandler(val1, val2) {
console.log(val1, val2)
}
window.addEventListener("scroll", preventJitter(scrollHandler, 300, "页面!!!", "滚动啦!!!"))
</script>
节流:在一次触发执行后,一定时间内,不让它再次执行,时间过了,再次触发才可以执行
节流封装:
function reduceExpenditure(fn, time) {
let timer = null
let _this = this
let arg = Array.from(arguments)
arg.splice(0, 2)
return function () {
if (!timer) {
let _this = this
fn.apply(_this,arg)
timer = setTimeout(function () {
timer = null
}, time)
}
}
}
function scrollHandler(val1, val2) {
console.log(val1, val2)
}
let ele = document.getElementsByTagName("body")[0]
ele.addEventListener("click", reduceExpenditure(scrollHandler, 2000, "页面!!!", "点击啦!!!"))