防抖 & 节流

防抖

防抖(debounce)指的是:频繁触发某个操作时,只执行最后一次。

场景:搜索框只在输入完后,才执行查询的请求。

好处:这样可以有效减少请求的次数,节省网络资源。

 <input type="button" value="点击">
let timeId
document.querySelector('input').onclick = function() {

// 清除之前的定时器
clearTimeout(timeId)
// 创建定时器
timeId = setTimeout(function(){
  console.log('客户端发送请求...')
  console.log('服务端返回数据...')
},1000)

节流

节流(throttle)指的是:单位时间内,频繁触发同一个操作,只会触发 1 次。

let old = 0
document.querySelector('input').onclick = function() {
  let now = Date.now()
  if(now - old >= 1000){
    console.log('客户端发送请求...')
    console.log('服务端返回数据...')
    old = now
  }
}
posted @ 2022-06-08 11:28  丫丫learning  阅读(33)  评论(0编辑  收藏  举报