UNPKG

@tienedev/datype

Version:

Modern TypeScript utility library with pragmatic typing and zero dependencies

87 lines 3.01 kB
/** * Options for configuring throttle behavior */ export interface ThrottleOptions { /** * If true, the function is called on the leading edge of the wait period. * @default true */ leading?: boolean; /** * If true, the function is called on the trailing edge of the wait period. * @default true */ trailing?: boolean; } /** * Throttled function interface with additional control methods */ export interface ThrottledFunction<TArgs extends readonly unknown[], TReturn> { /** * Call the throttled function */ (...args: TArgs): TReturn | undefined; /** * Cancel any pending execution */ cancel(): void; /** * Immediately execute the function with the last provided arguments */ flush(): TReturn | undefined; /** * Check if there's a pending execution */ pending(): boolean; } /** * Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds. * The throttled function comes with a `cancel` method to cancel delayed `func` invocations and * a `flush` method to immediately invoke them. * * @template TArgs - The argument types of the function * @template TReturn - The return type of the function * @param func - The function to throttle * @param wait - The number of milliseconds to throttle invocations to * @param options - Options object to configure throttle behavior * @returns A new throttled function with cancel, flush, and pending methods * * @example * ```typescript * import { throttle } from 'datype'; * * // Basic throttling - limits execution to once per 300ms * const throttledScroll = throttle((event: Event) => { * console.log('Scroll event processed'); * updateScrollPosition(); * }, 300); * * window.addEventListener('scroll', throttledScroll); * * // API rate limiting - ensure function is called at most once per second * const throttledApiCall = throttle(async (data: any) => { * return await fetch('/api/data', { * method: 'POST', * body: JSON.stringify(data) * }); * }, 1000); * * // Leading edge only - execute immediately, then ignore subsequent calls * const buttonClickHandler = throttle(() => { * console.log('Button clicked!'); * }, 1000, { leading: true, trailing: false }); * * // Trailing edge only - wait for quiet period, then execute with latest args * const searchHandler = throttle((query: string) => { * performSearch(query); * }, 300, { leading: false, trailing: true }); * * // Control methods * const throttled = throttle(() => console.log('Hello'), 1000); * throttled.cancel(); // Cancel pending execution * throttled.flush(); // Execute immediately * throttled.pending(); // Check if execution is pending * ``` */ export declare function throttle<TArgs extends readonly unknown[], TReturn>(func: (...args: TArgs) => TReturn, wait: number, options?: ThrottleOptions): ThrottledFunction<TArgs, TReturn>; //# sourceMappingURL=index.d.ts.map