函数防抖与节流

93 阅读1分钟

函数防抖

防抖:单位时间内,一个事件被频繁触发,让其只会触发**最后一次**

实现方法: 1.设置一个全局的变量用于接收定时器的id 2. 在事件回调中先清除定时器 3. 再设置一个一次性定时器,定时器设定的时间为单位时间 以应用频繁的搜索框下拉商品列表为例:

<input type="text">
<script>
let timerId = null
document.querySelector('input').addEventListener('input', function () {
  clearTimeout(timerId)
  timerId = setTimeout(() => {
    console.log(`对${this.value}发送ajax请求`)
  }, 500)
})
</script>

输入框每次输入状态变化都会对服务器发送ajax数据请求,为了减小服务器压力可以对该事件优化防抖,提高网页性能,减小服务器压力