debounce-promise-modern
v1.0.0
Published
Debounce async functions with Promise interface; only last call resolves.
Maintainers
Readme
debounce-promise-modern
Debounce async functions and return a promise. Only the last call resolves. Options include immediate, maxWait, and a cancel() method. Zero runtime dependencies.
Install
npm i debounce-promise-modernUsage
import debouncePromise from 'debounce-promise-modern'
const fetchUser = async (id: string) => {
const res = await fetch(`/api/users/${id}`)
return res.json()
}
const debouncedFetch = debouncePromise(fetchUser, 200, { immediate: false, maxWait: 1000 })
// Only the last call resolves
debouncedFetch('a')
debouncedFetch('b')
debouncedFetch('c').then(console.log)
// Cancel pending
debouncedFetch.cancel()API
debouncePromise(fn, wait, options?)→ returns a debounced functionimmediate(boolean): execute on leading edge; if newer calls arrive, only the last resolvesmaxWait(ms): guarantees a call after this time despite frequent triggerscancel(): rejects the current pending promise with{ name: 'CanceledError' }
Behavior Diagram
sequenceDiagram
participant C as Calls
participant D as Debounced
participant F as fn(...)
C->>D: call(1)
Note over D: immediate? leading invoke
D->>F: exec(1)
C->>D: call(2)
Note over D: previous promise canceled
C->>D: call(3)
D-->>F: trailing exec(3)
F-->>D: resolve(3)
D-->>C: Promise resolves for last callBuild
ESM + CJS via tsup. Types included. Package is tree-shakeable and minimal (<2KB minified bundle).
