# 202106

##防抖(debounce)和节流(throttle)

防抖:让某个时间期限内,事件处理函数只执行一次

/**
 * fn [function] 需要防抖的函数
 * delay [number] 毫秒,防抖期限值
 * */
function debounce (fn, delay) {
    let timer = null //借助闭包
    return function () {
      if(timer){
        clearTimeout(timer)
      }
      timer = setTimeout(fn, delay)
    }
}
//案例
function showTop () {
  var scrollTop = document.body.scrollTop || document.documentElement.scrollTop
  console.log('滚动条位置:' + scrollTop)
}

window.onscroll = debounce(showTop, 1000)
Last Updated: 7/1/2021, 2:02:35 PM