具有配置项和取消能力的防抖节流函数

防抖

使用isDebouncing判断是否处于防抖窗口 deboTimer是重置isDebouncing计时器的id

  • 非窗口期间调用函数 会设置窗口.如果leading为true,调用fn
  • 窗口期间调用函数 会重置窗口持续时间 并在窗口结束时以当前参数(也是最后一次参数)调用fn
js 复制代码
export const debo = (fn, options = {}) => {
  const {
    leading = false, // 是否立即执行
    trailing = true, // 是否执行最后一次
    delay = 200,
  } = options

  let isDebouncing // 是否处于防抖窗口
  let deboTimer // 重置isDebouncing的计时器id

  function deboFn(...args) {
    if (!isDebouncing) {
      if (leading) {
        fn.call(this, ...args)
      }
      // 不处于防抖窗口时 将isDebouncing设为true持续delay毫秒
      isDebouncing = true
      deboTimer = setTimeout(() => {
        isDebouncing = false
      }, delay)
    } else {
      // 处于防抖窗口时 重置窗口的持续时间
      clearTimeout(deboTimer)
      deboTimer = setTimeout(() => {
        isDebouncing = false
        if (trailing) {
          // 在当前窗口结束后 以最后一次的参数调用fn
          fn.call(this, ...args)
        }
      }, delay)
    }
  }
  const cancel = () => {
    clearTimeout(deboTimer)
    isDebouncing = false
  }
  return {
    deboFn,
    cancel,
  }
}

节流

使用isThrottling判断是否处于防抖窗口 throTimer是重置isThrottling计时器的id lastArgs是最后一次调用此函数的参数

  • 非窗口期间调用函数,如果leading为true,调用fn(不会设置lastArgs).设置窗口.在窗口结束时,以lastArgs调用fn,将lastArgs设置为null.
  • 窗口期间调用函数 不会重置窗口持续时间.保存当前参数至lastArgs
js 复制代码
export const thro = (fn, options = {}) => {
  const {
    leading = true, // 是否立即执行
    trailing = false, // 是否执行最后一次
    delay = 200,
  } = options

  let isThrottling // 是否处于节流窗口
  let throTimer // 重置isThrottling的计时器id
  let lastArgs

  function throFn(...args) {
    if (!isThrottling) {
      if (leading) {
        fn.call(this, ...args)
      }
      // 不处于节流窗口时 将isThrottling设为true持续delay毫秒
      isThrottling = true
      throTimer = setTimeout(() => {
        isThrottling = false
        if (trailing && lastArgs) {
          // 在当前窗口结束后 以最后一次的参数调用fn
          fn.call(this, ...lastArgs)
          lastArgs = null
        }
      }, delay)
    } else {
      // 处于节流窗口时 不干涉其持续时间
      // 记录当前args 供窗口结束时可能的调用
      lastArgs = args
    }
  }
  const cancel = () => {
    clearTimeout(throTimer)
    isThrottling = true
    lastArgs = null
  }

  return {
    throFn,
    cancel,
  }
}
相关推荐
C_心欲无痕4 小时前
前端实现水印的两种方式:SVG 与 Canvas
前端·安全·水印
尾善爱看海7 小时前
不常用的浏览器 API —— Web Speech
前端
美酒没故事°7 小时前
vue3拖拽+粘贴的综合上传器
前端·javascript·typescript
jingling5558 小时前
css进阶 | 实现罐子中的水流搅拌效果
前端·css
悟能不能悟10 小时前
前端上载文件时,上载多个文件,但是一个一个调用接口,怎么实现
前端
可问春风_ren10 小时前
前端文件上传详细解析
前端·ecmascript·reactjs·js
羊小猪~~11 小时前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3
晚风资源组12 小时前
CSS文字和图片在容器内垂直居中的简单方法
前端·css·css3
Miketutu12 小时前
Flutter学习 - 组件通信与网络请求Dio
开发语言·前端·javascript
摘星编程13 小时前
React Native for OpenHarmony 实战:Swiper 滑动组件详解
javascript·react native·react.js