Framework
Version
Debouncer API Reference
Throttler API Reference
Rate Limiter API Reference
Queue API Reference
Batcher API Reference

AsyncThrottler

Class: AsyncThrottler<TFn>

Defined in: async-throttler.ts:180

A class that creates an async throttled function.

Throttling limits how often a function can be executed, allowing only one execution within a specified time window. Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a regular interval regardless of how often it's called.

Unlike the non-async Throttler, this async version supports returning values from the throttled function, making it ideal for API calls and other async operations where you want the result of the maybeExecute call instead of setting the result on a state variable from within the throttled function.

This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to ensure a maximum execution frequency.

Error Handling:

  • If an onError handler is provided, it will be called with the error and throttler instance
  • If throwOnError is true (default when no onError handler is provided), the error will be thrown
  • If throwOnError is false (default when onError handler is provided), the error will be swallowed
  • Both onError and throwOnError can be used together - the handler will be called before any error is thrown
  • The error state can be checked using the underlying AsyncThrottler instance

State Management:

  • Uses TanStack Store for reactive state management
  • Use initialState to provide initial state values when creating the async throttler
  • Use onSuccess callback to react to successful function execution and implement custom logic
  • Use onError callback to react to function execution errors and implement custom error handling
  • Use onSettled callback to react to function execution completion (success or error) and implement custom logic
  • The state includes error count, execution status, last execution time, and success/settle counts
  • State can be accessed via asyncThrottler.store.state when using the class directly
  • When using framework adapters (React/Solid), state is accessed from asyncThrottler.state

Example

ts
const throttler = new AsyncThrottler(async (value: string) => {
  const result = await saveToAPI(value);
  return result; // Return value is preserved
}, {
  wait: 1000,
  onError: (error) => {
    console.error('API call failed:', error);
  }
});

// Will only execute once per second no matter how often called
// Returns the API response directly
const result = await throttler.maybeExecute(inputElement.value);
const throttler = new AsyncThrottler(async (value: string) => {
  const result = await saveToAPI(value);
  return result; // Return value is preserved
}, {
  wait: 1000,
  onError: (error) => {
    console.error('API call failed:', error);
  }
});

// Will only execute once per second no matter how often called
// Returns the API response directly
const result = await throttler.maybeExecute(inputElement.value);

Type Parameters

TFn extends AnyAsyncFunction

Constructors

new AsyncThrottler()

ts
new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>
new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>

Defined in: async-throttler.ts:191

Parameters

fn

TFn

initialOptions

AsyncThrottlerOptions<TFn>

Returns

AsyncThrottler<TFn>

Properties

options

ts
options: AsyncThrottlerOptions<TFn>;
options: AsyncThrottlerOptions<TFn>;

Defined in: async-throttler.ts:184


store

ts
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;

Defined in: async-throttler.ts:181

Methods

cancel()

ts
cancel(): void
cancel(): void

Defined in: async-throttler.ts:401

Cancels any pending execution or aborts any execution in progress

Returns

void


flush()

ts
flush(): void
flush(): void

Defined in: async-throttler.ts:356

Processes the current pending execution immediately

Returns

void


maybeExecute()

ts
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>

Defined in: async-throttler.ts:273

Attempts to execute the throttled function. The execution behavior depends on the throttler options:

  • If enough time has passed since the last execution (>= wait period):

    • With leading=true: Executes immediately
    • With leading=false: Waits for the next trailing execution
  • If within the wait period:

    • With trailing=true: Schedules execution for end of wait period
    • With trailing=false: Drops the execution

Parameters

args

...Parameters<TFn>

Returns

Promise<undefined | ReturnType<TFn>>

Example

ts
const throttled = new AsyncThrottler(fn, { wait: 1000 });

// First call executes immediately
await throttled.maybeExecute('a', 'b');

// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');
const throttled = new AsyncThrottler(fn, { wait: 1000 });

// First call executes immediately
await throttled.maybeExecute('a', 'b');

// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');

reset()

ts
reset(): void
reset(): void

Defined in: async-throttler.ts:409

Resets the debouncer state to its default values

Returns

void


setOptions()

ts
setOptions(newOptions): void
setOptions(newOptions): void

Defined in: async-throttler.ts:206

Updates the async throttler options

Parameters

newOptions

Partial<AsyncThrottlerOptions<TFn>>

Returns

void

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.