防抖与节流
防抖与节流的本质其实是差不多的,都是为了减少调用频率,提高前端性能。
防抖是在一段时间内,只执行最后一次的操作。
节流是在执行事件时,每隔一段时间有规律进行运行。
防抖:一般用于input输入框查询事件,或者按钮点击事件较多
<button id="btn">提交</button>
<script>
let btn = document.getElementById('btn')
let timer = null
btn.addEventListener('click', function() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
console.log(1)
}, 1000)
})
</script>
节流:一般用于滚动事件较多
<style>
body{
height: 2000px;
}
</style>
<script>
window.onscroll = fun(function() {
console.log('节流输出')
}, 2000)
let timer = null
function fun(fn, delay) {
let flg = true
return function() {
if (flg) {
timer = setTimeout(() => {
fn.call(this)
flg = true
}, 1000)
}
flg = false
}
}
</script>

浙公网安备 33010602011771号