Search Docs
debounce
创建一个防抖函数,该函数会延迟调用,直到自上次调用后经过指定的等待时间。
import { debounce } from 'funtool'; // 基本用法 const debouncedLog = debounce((message) => { console.log(message); }, 300); debouncedLog('Hello'); // 仅在 300 毫秒无操作后才会记录日志 // 带 this 上下文 const obj = { prefix: 'Log: ', log: debounce(function(msg) { console.log(this.prefix + msg); }, 200) }; obj.log('Test'); // 输出: Log: Test // 控制方法 const fn = debounce(() => console.log('Done'), 500); fn(); fn.cancel(); // 取消待执行的调用 fn.flush(); // 立即执行 fn.pending(); // 检查是否有待执行的调用
type Debounced<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 } function debounce<T extends (...args: any[]) => any, This = any>( fn: T, delay?: number ): Debounced<T, This>
fn
delay
返回一个带有额外控制方法的防抖函数:
cancel()
flush()
pending()
this
debounceSync