JavaScript 防抖节流

debounce (防抖)

因频繁执行 DOM 操作, 资源加载等行为, 导致 UI 停顿甚至浏览器崩溃

  • window 对象频繁的 onresize, onscroll等事件
  • 拖拽的mousemove事件
  • 资源加载的load事件
  • 文字输入, 自动完成的keyup事件

比如每次搜索框内每输入一下就会向服务器发送一个请求, 这样既没有意义, 也很浪费资源

实际上我们更希望搜索框内当有一段时间内没有再发生输入事件时, 此时再向服务器发送请求会更有利与页面性能和缓解服务器压力

function debounce(func, delay = 100) {
  let timer = null
  return function () {
    let that = this
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      func && func.apply(that, args)
    }, delay)
  }
}

throttle (节流)

节流分为时间戳定时器版

节流单纯的降低代码执行的频率, 保证一段时间内核心代码只执行一次

时间戳版定时器版的节流函数的区别

  • 时间戳版的函数触发是在时间段内开始的时候
  • 定时器版的函数触发是在时间段内结束的时候

时间戳版

function throttle(func, wait = 100) {
  let lastTime = 0
  return function () {
    let nowTime = new Date().getTime()
    if (nowTime - lastTime > wait) {
      func && func.apply(this, arguments)
      lastTime = nowTime
    }
  }
}

定时器版

function throttle(func, delay = 100) {
  let timer = null
  return function () {
    let that = this
    let args = arguments
    if (!timer) {
      timer = setTimeout(() => {
        func && func.apply(that, args)
        timer = null
      }, delay)
    }
  }
}

防抖与节流的区别

  • 防抖: 在规定时间内不再有新的调用后执行一次函数
  • 节流: 保证一段时间内执行一次函数
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容