throttle

创建一个节流版本的异步函数,确保在指定时间间隔内最多执行一次。

使用场景

  • 事件处理:限制频繁的事件回调
  • API调用:防止过多的API请求
  • 用户输入:处理快速的用户交互
  • 动画:控制动画帧率

示例

import { throttle } from 'funtool';

// 基本异步节流
const throttledFetch = throttle(async (url) => {
  const res = await fetch(url);
  return res.json();
}, 1000);

// 使用控制方法
const fn = throttle(() => console.log('执行'), 500);
fn();
fn.cancel(); // 取消待执行
fn.flush(); // 立即执行
fn.pending(); // 检查是否有待执行

函数签名

function throttle<T extends (...args: any[]) => any, This = any>(
  fn: T,
  interval?: number
): Throttled<T, This>

interface Throttled<T extends (...args: any[]) => any, This = any> {
  (this: This, ...args: Parameters<T>): Promise<ReturnType<T> | undefined>;
  cancel: () => void;
  flush: () => Promise<ReturnType<T> | undefined>;
  pending: () => boolean;
}

参数

  • fn: 需要节流的异步函数
  • interval: 节流间隔,毫秒(默认: 500)

返回值

返回一个带有额外控制方法的节流函数:

  • cancel(): 取消待执行
  • flush(): 立即执行
  • pending(): 检查是否有待执行

注意事项

  • 保持正确的this上下文
  • 返回解析为原函数返回值的Promise
  • debounce类似但时间行为不同
  • 同步函数请使用throttleSync