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

防抖

使用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,
  }
}
相关推荐
OLong14 分钟前
React Update Queue 源码全链路解析:从 setState 到 DOM 更新
前端·react.js
知识浅谈17 分钟前
OpenLayers与Vue.js结合实现前端地图应用
前端
掘金0124 分钟前
Vue3 项目中实现特定页面离开提示保存功能方案
javascript·vue.js
答案answer37 分钟前
three.js 实现几个好看的文本内容效果
前端·webgl·three.js
余_弦43 分钟前
区块链钱包开发(十九)—— 构建账户控制器(AccountsController)
javascript·区块链·以太坊
Running_C1 小时前
一文读懂跨域
前端·http·面试
前端Hardy1 小时前
HTML&CSS:有趣的小铃铛
javascript·css·html
南囝coding1 小时前
这个Web新API让任何内容都能画中画!
前端·后端
起这个名字1 小时前
Vue2/3 v-model 使用区别详解,不了解的来看看
前端·javascript·vue.js
林太白1 小时前
VitePress项目工程化应该如何做
前端·后端