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

防抖

使用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,
  }
}
相关推荐
BD_Marathon18 小时前
Promise基础语法
开发语言·前端·javascript
BOF_dcb18 小时前
网页设计DW
前端
千寻girling18 小时前
计算机组成原理-全通关源码-实验(通关版)---头歌平台
前端·面试·职场和发展·typescript·node.js
karshey19 小时前
【前端】解决:点击一个button,发现不触发点击事件
前端
用泥种荷花19 小时前
【前端学习AI】Function Calling
前端
2301_7965125219 小时前
ModelEngin平台开发工作流,“前端职业导航师”通过直观的图形化界面,让用户像“搭积木”一样,轻松串联各种智能节点
前端·modelengine
Aotman_19 小时前
JavaScript MutationObserver用法( 监听DOM变化 )
开发语言·前端·javascript·vue.js·前端框架·es6
酷柚易汛19 小时前
酷柚易汛ERP 2025-12-26系统升级日志
java·前端·数据库·php
Onlyᝰ19 小时前
前端调用接口进行上传文件
前端
90后的晨仔19 小时前
2025,我的“AI搭子”:那个我以为用不上的AI,成了我每天都离不开的搭档!!
前端