2.节流函数(throttle)

✨ 一、什么是节流(Throttle)?

📌 定义:

节流(throttle)是指一定时间间隔内只执行一次函数,无论这段时间内函数被触发了多少次。

常见的应用场景包括:

  • 页面滚动(scroll

  • 页面缩放(resize

  • 高频点击(如按钮点透)

  • 拖拽事件(drag

  • 鼠标移动(mousemove


🧠 二、节流 vs 防抖(debounce)

对比点防抖(debounce)节流(throttle)
触发机制停止触发后执行一次固定时间内只触发一次
关键实现clearTimeout + setTimeoutsetTimeout时间戳比较
使用场景输入框联想、搜索防抖滚动加载、点击防抖

🛠 三、节流函数的几种实现方式

✅ 1. 时间戳版 throttle(立即执行)

function throttle(fn, delay) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime > delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
}

✅ 2. 定时器版 throttle(最后一次也会触发)

function throttle(fn, delay) {
  let timer = null;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args);
        timer = null;
      }, delay);
    }
  };
}

✅ 3. 混合版 throttle(立即执行 + 结束后再执行一次)

function throttle(fn, delay) {
  let timer = null;
  let lastTime = 0;

  return function (...args) {
    const now = Date.now();
    const remaining = delay - (now - lastTime);

    if (remaining <= 0) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      fn.apply(this, args);
      lastTime = now;
    } else if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args);
        lastTime = Date.now();
        timer = null;
      }, remaining);
    }
  };
}

🧪 四、节流函数的使用场景示例

🎯 1. 页面滚动节流

window.addEventListener("scroll", throttle(() => {
  console.log("页面滚动:", new Date().toISOString());
}, 200));

🎯 2. 按钮点击节流

<button id="btn">点击我</button>
<script>
  document.getElementById("btn").addEventListener("click", throttle(() => {
    console.log("点击执行:", new Date().toISOString());
  }, 1000));
</script>

🔧 五、TypeScript 版本 throttle 函数

function throttle<T extends (...args: any[]) => void>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timer: number | null = null;
  return function (...args: Parameters<T>) {
    if (timer === null) {
      timer = window.setTimeout(() => {
        fn(...args);
        timer = null;
      }, delay);
    }
  };
}

🎁 六、Vue 中的 throttle 使用方法

如果你想在 Vue 项目中使用,可以:

  • 通过自定义指令 v-throttle

  • 在 Composition API 的事件中包裹 throttle

✅ 功能特性

  • 支持两种写法(函数 / 对象):

    • v-throttle="fn":默认事件为 click,默认 delay 为 300ms

    • v-throttle="{ handler: fn, delay: 1000, event: 'scroll' }"

  • 自动解绑事件,避免内存泄漏


📦 1. 新建指令文件 v-throttle.ts

// src/directives/v-throttle.ts
import type { DirectiveBinding } from "vue";

interface ThrottleOptions {
  handler: (...args: any[]) => void;
  delay?: number;
  event?: string;
}

function throttle(fn: (...args: any[]) => void, delay: number) {
  let timer: number | null = null;
  return function (this: unknown, ...args: any[]) {
    if (timer === null) {
      fn.apply(this, args);
      timer = window.setTimeout(() => {
        timer = null;
      }, delay);
    }
  };
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding<ThrottleOptions | Function>) {
    let eventName = "click";
    let delay = 300;
    let handler: (...args: any[]) => void;

    if (typeof binding.value === "function") {
      handler = binding.value;
    } else if (binding.value && typeof binding.value.handler === "function") {
      handler = binding.value.handler;
      delay = binding.value.delay ?? delay;
      eventName = binding.value.event ?? eventName;
    } else {
      console.warn("v-throttle:传入必须是函数或包含 handler 的对象");
      return;
    }

    const throttled = throttle(handler, delay);
    (el as any).__throttleHandler__ = throttled;
    el.addEventListener(eventName, throttled);
  },
  beforeUnmount(el: HTMLElement, binding: DirectiveBinding) {
    const eventName =
      typeof binding.value === "object" ? binding.value.event ?? "click" : "click";
    el.removeEventListener(eventName, (el as any).__throttleHandler__);
    delete (el as any).__throttleHandler__;
  },
};

🔧 2. 注册全局指令(main.ts)

import { createApp } from "vue";
import App from "./App.vue";
import vThrottle from "./directives/v-throttle";

const app = createApp(App);
app.directive("throttle", vThrottle);
app.mount("#app");

🧪 3. 使用示例

✅ 写法 1:默认绑定 click 事件、默认 300ms 节流

<template>
  <button v-throttle="handleClick">点击我(节流)</button>
</template>

<script setup lang="ts">
function handleClick() {
  console.log("按钮被点击!");
}
</script>

✅ 写法 2:绑定 scroll 事件,设置延迟时间

<template>
  <div
    class="h-96 overflow-auto border"
    v-throttle="{ handler: handleScroll, delay: 500, event: 'scroll' }"
  >
    <div style="height: 1000px">滚动容器</div>
  </div>
</template>

<script setup lang="ts">
function handleScroll() {
  console.log("scroll 触发!");
}
</script>

📌 七、总结

点评内容
优点限制函数执行频率,提升性能
缺点某些关键操作可能被跳过
推荐方式推荐使用“时间戳 + 定时器”的组合版,兼顾首次和尾部触发


📚 八、参考资料

  • MDN Event Throttle

  • Lodash throttle 源码解析

  • JS 节流防抖总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉檀迦俐

你的鼓励奖是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值