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

防抖

使用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,
  }
}
相关推荐
fcm191 天前
(6) tauri之前端框架性能对比
前端·javascript·rust·前端框架·vue·react
今晚务必早点睡1 天前
前端缓存好还是后端缓存好?缓存方案实例直接用
前端·后端·缓存
双普拉斯1 天前
微信小程序通用弹窗组件封装与动画实现
javascript·html5
IT_陈寒1 天前
Vue3性能优化:5个被低估的Composition API技巧让我打包体积减少了40% 🚀
前端·人工智能·后端
x007xyz1 天前
🚀🚀🚀前端的无限可能-纯Web实现的字幕视频工具 FlyCut Caption
前端·openai·音视频开发
前端Hardy1 天前
HTML&CSS: 在线电子签名工具
前端·javascript·canvas
biomooc1 天前
D3.js 与数据可视化
开发语言·javascript·信息可视化
前端Hardy1 天前
告别抽象!可视化动画带你学习算法——选择排序
前端·javascript·css
毕设十刻1 天前
基于vue的考研信息系统6kv17(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js
望获linux1 天前
论文解读:利用中断隔离技术的 Linux 亚微秒响应性能优化
java·linux·运维·前端·arm开发·数据库·性能优化