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

防抖

使用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,
  }
}
相关推荐
AiXed8 分钟前
PC微信协议之AES-192-GCM算法
前端·数据库·python
AllData公司负责人10 分钟前
实时开发平台(Streampark)--Flink SQL功能演示
大数据·前端·架构·flink·开源
小满zs34 分钟前
Next.js第五章(动态路由)
前端
清沫37 分钟前
VSCode debugger 调试指南
前端·javascript·visual studio code
一颗宁檬不酸1 小时前
页面布局练习
前端·html·页面布局
zhenryx2 小时前
React Native 自定义 ScrollView 滚动条:开箱即用的 IndicatorScrollView(附源码示例)
javascript·react native·react.js·typescript
金木讲编程2 小时前
Claude、Agent与Copilot协作生成Angular应用
前端·ai编程
振华OPPO3 小时前
Vue:“onMounted“ is defined but never used no-unused-vars
前端·javascript·css·vue.js·前端框架
欧雷殿3 小时前
在富阳银湖成立地域化的软件研发团队
前端·程序员·创业
狂炫冰美式4 小时前
前端实时推送 & WebSocket 面试题(2026版)
前端·http·面试