debounce

function

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.

Signature

debounce<T extends (...args: any[]) => any>(func: T, wait?: number, options?: { leading?: boolean; trailing?: boolean; maxWait?: number }): T & { cancel: () => void; flush: () => void }

Parameters

NameTypeDescription
funcTThe function to debounce
wait?numberThe number of milliseconds to delayDefault: 0
options?{ leading?: boolean; trailing?: boolean; maxWait?: number }The options object

Returns

T & { cancel: () => void; flush: () => void } - Returns the new debounced function

Examples

Basic Usage

import { debounce } from 'dashlite'

const debounced = debounce(() => console.log('Hello'), 1000)
debounced()
debounced()
debounced()
// => 'Hello' (only once after 1000ms)

With Cancel

import { debounce } from 'dashlite'

const debounced = debounce(() => console.log('Hello'), 1000)
debounced()
debounced.cancel() // Cancels pending invocation

With Flush

import { debounce } from 'dashlite'

const debounced = debounce(() => console.log('Hello'), 1000)
debounced()
debounced.flush() // Immediately invokes pending function

Notes

  • The debounced function comes with a cancel method to cancel delayed invocations
  • The debounced function comes with a flush method to immediately invoke them

Available since version 1.0.0