防抖、节流实现方式

防抖、节流

开发中经常会有一些持续触发的事件,比如scroll、resize、mousemove、input等。频繁的执行回调,不仅对性能有很大影响,甚至会有相应跟不上,造成页面卡死等现象。

针对这种问题有两种解决方案,防抖和节流。

防抖

事件触发后的time时间内只执行一次。原理是维护一个延时器,规定在time时间后执行函数,如果在time时间内再次触发,则取消之前的延时器重新设置。所以回调只在最后执行一次。

  1. 方式一:
function debounce(func, time = 0) {
  if (typeof func !== 'function') {
    throw new TypeError('Expect a function')
  }

  let timer

  return function (e) {
    if (timer) {
      clearTimeout(timer)
    }

    timer = setTimeout(() => {
      func.call(this, e)
      clearTimeout(timer)
    }, time)
  }
}
  1. 方式二:
const debounce = (func, wait = 0) => {
  let timeout = null
  let args
  function debounced(...arg) {
    args = arg
    if(timeout) {
      clearTimeout(timeout)
      timeout = null
    }
    // 以Promise的形式返回函数执行结果
    return new Promise((res, rej) => {
      timeout = setTimeout(async () => {
        try {
          const result = await func.apply(this, args)
          res(result)
        } catch(e) {
          rej(e)
        }
      }, wait)
    })
  }
  // 允许取消
  function cancel() {
    clearTimeout(timeout)
    timeout = null
  }
  // 允许立即执行
  function flush() {
    cancel()
    return func.apply(this, args)
  }
  debounced.cancel = cancel
  debounced.flush = flush
  return debounced
}

节流

在事件触发过程中,每隔wait执行一次回调。

可选参数三 trailing,事件第一次触发是否执行一次回调。默认true,即第一次触发先执行一次。

  1. 方式一:
function throttle(func, wait = 0, trailing = true) {
  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }

  let timer
  let start = +new Date

  return function (e) {
    const now = +new Date
    const distance = start + wait - now

    if (timer) {
      clearTimeout(timer)
    }
    if (now - start >= wait || trailing) { // 每个wait时间执行一次或第一次触发就执行一次
      func.apply(this, rest)
      start = now
      trailing = false
    } else {
      // 事件结束wait时间后再执行一次
      timer = setTimeout(() => {
        func.call(this, e)
      }, distance )
    }
  }
}
  1. 方式二:
function throttlew(fn, wait) {
    let start = 0

    return function(e) {
        const now = Date.now()
        if (now - start > wait) {
            fn.call(this, e)
            start = now
        }
 }    

  1. 方式三:
const throttle = (func, wait = 0, execFirstCall) => {
    let timeout = null
    let args
    let firstCallTimestamp

    function throttled(...arg) {
      if (!firstCallTimestamp) firstCallTimestamp = new Date().getTime()
      if (!execFirstCall || !args) {
        // console.log('set args:', arg)
        args = arg
      }
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      // 以Promise的形式返回函数执行结果
      return new Promise(async (res, rej) => {
        if (new Date().getTime() - firstCallTimestamp >= wait) {
          try {
            const result = await func.apply(this, args)
            res(result)
          } catch (e) {
            rej(e)
          } finally {
            cancel()
          }
        } else {
          timeout = setTimeout(async () => {
            try {
              const result = await func.apply(this, args)
              res(result)
            } catch (e) {
              rej(e)
            } finally {
              cancel()
            }
          }, firstCallTimestamp + wait - new Date().getTime())
        }
      })
    }
    // 允许取消
    function cancel() {
      clearTimeout(timeout)
      args = null
      timeout = null
      firstCallTimestamp = null  // 这里很关键。每次执行完成后都要初始化
    }
    // 允许立即执行
    function flush() {
      cancel()
      return func.apply(this, args)
    }
    throttled.cancel = cancel
    throttled.flush = flush
    return throttled
  }

区别: 不管事件触发有多频繁,节流都会保证在规定时间内一定会执行一次真正的事件处理函数,而防抖只是在最后一次事件触发后才执行一次函数。

场景:

防抖:比如监听页面滚动,滚动结束并且到达一定距离时显示返回顶部按钮,适合使用防抖。

节流:比如在页面的无限加载场景下,需要用户在滚动页面时过程中,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。此场景适合用节流来实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 防抖和节流 相同:在不影响客户体验的前提下,将频繁的回调函数,进行次数缩减.避免大量计算导致的页面卡顿.不同:防抖...
    CodeMT阅读 428评论 0 2
  • 本篇课题,或许早已是烂大街的解读文章。不过春招系列面试下来,不少伙伴们还是似懂非懂地栽倒在(~面试官~)深意的笑容...
    以乐之名阅读 1,894评论 0 9
  • 前言 props与state都是用于组件存储数据的一js对象,前者是对外暴露数据接口,后者是对内组件的状态,它们决...
    itclanCoder阅读 2,243评论 0 0
  • 前言 最近和前端的小伙伴们,在讨论面试题的时候。谈到了函数防抖和函数节流的应用场景和原理。于是,想深入研究一下两者...
    youthcity阅读 23,831评论 5 78
  • 我们大家都知道有一个《明日歌》明日复明日,明日何其多。我生待明日,万事成蹉脱。就是说,许多人做事情总是等待明天开始...
    胜利一号阅读 1,251评论 0 0

友情链接更多精彩内容