什么是防抖?
在一段时间内频繁触发某个事件,只会执行最后一次,也就是说将多次触发变成了一次触发
防抖的好处
避免频繁的调用服务器资源,给服务器带来压力
代码示范:
/* css样式 */
<style>
input {
width: 200px;
height: 25px;
outline: none;
border: 1px solid skyblue;
}
button {
width: 50px;
height: 28px;
background-color: skyblue;
border: none;
cursor: pointer;
}
</style>
<!-- body中的代码 -->
<body>
<input type="text">
<button>提交</button>
<script>
// 获取元素
let btn = document.querySelector('button')
let count = 0
// 如果频繁点击btn按钮,会被触发很多次
// 要限制触发的频率,比如:如果是在300毫秒内重复点击了btn,那么则不去执行count++
btn.addEventListener('click', function () {
clearTimeout(this.timerId) // 只要是在300毫秒内频繁点击了按钮,都不会执行
// this.timerId 表示当前浏览器的一个标识
this.timerId = setTimeout(function () {
count++
console.log(`我被点击了${count}次`)
}, 300)
})
</script>
</body>