Framework
Version
防抖器 API 參考
節流器 API 參考
速率限制器 API 參考
佇列 API 參考

Debouncer

Class: Debouncer<TFn>

Defined in: debouncer.ts:65

A class that creates a debounced function.

Debouncing ensures that a function is only executed after a certain amount of time has passed since its last invocation. This is useful for handling frequent events like window resizing, scroll events, or input changes where you want to limit the rate of execution.

The debounced function can be configured to execute either at the start of the delay period (leading edge) or at the end (trailing edge, default). Each new call during the wait period will reset the timer.

Example

ts
const debouncer = new Debouncer((value: string) => {
  saveToDatabase(value);
}, { wait: 500 });

// Will only save after 500ms of no new input
inputElement.addEventListener('input', () => {
  debouncer.maybeExecute(inputElement.value);
});
const debouncer = new Debouncer((value: string) => {
  saveToDatabase(value);
}, { wait: 500 });

// Will only save after 500ms of no new input
inputElement.addEventListener('input', () => {
  debouncer.maybeExecute(inputElement.value);
});

Type Parameters

TFn extends AnyFunction

Constructors

new Debouncer()

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

Defined in: debouncer.ts:72

Parameters

fn

TFn

initialOptions

DebouncerOptions<TFn>

Returns

Debouncer<TFn>

Methods

cancel()

ts
cancel(): void
cancel(): void

Defined in: debouncer.ts:144

Cancels any pending execution

Returns

void


getExecutionCount()

ts
getExecutionCount(): number
getExecutionCount(): number

Defined in: debouncer.ts:155

Returns the number of times the function has been executed

Returns

number


getIsPending()

ts
getIsPending(): boolean
getIsPending(): boolean

Defined in: debouncer.ts:162

Returns true if debouncing

Returns

boolean


getOptions()

ts
getOptions(): Required<DebouncerOptions<TFn>>
getOptions(): Required<DebouncerOptions<TFn>>

Defined in: debouncer.ts:98

Returns the current debouncer options

Returns

Required<DebouncerOptions<TFn>>


maybeExecute()

ts
maybeExecute(...args): void
maybeExecute(...args): void

Defined in: debouncer.ts:106

Attempts to execute the debounced function If a call is already in progress, it will be queued

Parameters

args

...Parameters<TFn>

Returns

void


setOptions()

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

Defined in: debouncer.ts:86

Updates the debouncer options Returns the new options state

Parameters

newOptions

Partial<DebouncerOptions<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.