calmfn
v1.2.0
Published
Debounce and throttle with cancel(), flush(), pending(), AbortSignal and promise-returning versions. Lodash timing, full TypeScript types, ESM + CommonJS, zero dependencies.
Maintainers
Readme
calmfn
Debounce and throttle for JavaScript and TypeScript, with cancel(), flush(), pending() and promise versions.
Some events fire many times per second: typing, scrolling, resizing. calmfn limits how often your function runs when that happens. It replaces lodash.debounce and lodash.throttle with the same timing rules, and adds promise versions, AbortSignal support and full TypeScript types.
Features
- Same timing as lodash:
leading,trailingandmaxWaitwork like inlodash.debounceandlodash.throttle. cancel(),flush()andpending()on every debounced and throttled function.- Promise versions:
debounceAsyncandthrottleAsyncreturn a promise for the result. Calls that are merged into one run get the same result. AbortSignalsupport: passsignaland the function cancels itself, for example when a component unmounts.- Typed: the returned function keeps the parameters and
thistype of your function. - Works with fake timers: it uses
setTimeoutandDate.now, so Vitest and Jest fake timers work in tests. - Zero dependencies, about 1.4 KB gzipped, ESM and CommonJS.
Installation
npm install calmfnpnpm add calmfn
yarn add calmfn
bun add calmfnQuick start
import { debounce, throttle, debounceAsync } from 'calmfn'
// debounce: wait until the calls stop for 300 ms, then run once
const save = debounce((text) => `saved: ${text}`, 300)
save('h')
save('he')
save('hello')
save.pending() // => true (a call is scheduled)
save.flush() // => 'saved: hello' (run it now, with the latest arguments)
// throttle: run at most once every 100 ms
const onScroll = throttle(() => console.log(window.scrollY), 100)
window.addEventListener('scroll', onScroll)
// debounceAsync: await the result of the debounced call
const search = debounceAsync(async (query) => [`${query} result`], 300)
search('c')
await search('cal') // => ['cal result']With CommonJS, use const { debounce, throttle } = require('calmfn').
Table of contents
Usage
Choose between debounce and throttle
Both take a function and a wait time in milliseconds. They differ in when your function runs:
- Debounce waits until the calls stop. It runs your function once,
waitms after the last call. Use it when only the final value matters, such as a search box or an autosave. - Throttle runs your function at most once every
waitms while the calls keep coming. Use it when you want regular updates during the activity, such as on scroll or resize.
Here a function is called every 50 ms for 250 ms, with wait = 100. Each * is one run of your function:
time (ms) 0 100 200 300 400
calls x x x x x x
debounce *
throttle * * * *Debounce runs once, 100 ms after the last call. Throttle runs right away, then every 100 ms, and once more at the end with the latest arguments.
Search as the user types
Debounce the search, so it runs when the user stops typing. Add maxWait (the longest time to wait) to also search at least once a second while the user keeps typing:
import { debounce } from 'calmfn'
const search = debounce((query) => runSearch(query), 300, { maxWait: 1000 })
input.addEventListener('input', (event) => search(event.target.value))Update the page on scroll or resize
Throttle the handler, so it runs at most once every 100 ms. The last event is never lost: if events came in during the wait, the handler runs once more at the end.
import { throttle } from 'calmfn'
const onResize = throttle(() => updateLayout(window.innerWidth), 100)
window.addEventListener('resize', onResize)Autosave a draft
Save 1 second after the user stops typing. Before the page closes, call flush() so the last edit is saved right away instead of lost.
import { debounce } from 'calmfn'
const save = debounce((text) => api.saveDraft(text), 1000)
editor.addEventListener('input', () => save(editor.value))
window.addEventListener('beforeunload', () => save.flush())pending() tells you if a save is still waiting. You can use it to warn the user, or to save before you leave a page:
router.beforeLeave(() => {
if (save.pending()) save.flush()
})Await the debounced result
debounceAsync returns a promise from every call. All calls that are merged into one run of your function get the same promise, so each caller can await the final result.
import { debounceAsync } from 'calmfn'
const checkName = debounceAsync(async (name) => {
const taken = await api.isTaken(name)
return taken ? 'taken' : 'ok'
}, 300)
checkName('a') // these three calls...
checkName('al')
await checkName('ali') // ...all resolve to the result for 'ali'fn can be sync or async. If it throws or rejects, all the merged calls reject with that error. For throttling with promises, use throttleAsync the same way.
Run on the first click only
With leading: true the function runs on the first call of a burst. With trailing: false it does not run again at the end. This runs on the first click and ignores repeat clicks until there is a 1 second pause:
import { debounce } from 'calmfn'
const submit = debounce(() => sendForm(), 1000, { leading: true, trailing: false })
button.addEventListener('click', submit)Cancel when a component unmounts
Pass an AbortSignal as signal. When it aborts, the scheduled call is dropped and later calls do nothing.
import { throttle } from 'calmfn'
const controller = new AbortController()
const onScroll = throttle(() => updateHeader(), 100, { signal: controller.signal })
window.addEventListener('scroll', onScroll, { signal: controller.signal })
// later, when the component unmounts:
controller.abort()You can also call cancel() yourself to drop the scheduled call.
Cancel waiting promises
With debounceAsync and throttleAsync, cancel() rejects the promises that are still waiting. By default they reject with a CancelError. Pass a reason to reject with your own value.
import { debounceAsync, CancelError } from 'calmfn'
const load = debounceAsync((id) => fetchUser(id), 300)
const promise = load(1)
load.cancel()
try {
await promise
} catch (error) {
error instanceof CancelError // => true
}You do not have to handle these rejections. Promises rejected by cancel() or by signal never cause "unhandled rejection" warnings, but await still sees the rejection.
Test with fake timers
calmfn uses setTimeout and Date.now, so fake timers in Vitest or Jest work:
import { vi, expect, test } from 'vitest'
import { debounce } from 'calmfn'
test('saves once after typing stops', () => {
vi.useFakeTimers()
const fn = vi.fn()
const save = debounce(fn, 300)
save('a')
save('ab')
vi.advanceTimersByTime(300)
expect(fn).toHaveBeenCalledOnce()
expect(fn).toHaveBeenCalledWith('ab')
})Use TypeScript types
The returned function has the same parameters and this type as your function:
import { debounce, debounceAsync } from 'calmfn'
const d = debounce((id: number, name?: string) => `${id} ${name}`, 100)
d(1, 'a') // d: Debounced<(id: number, name?: string) => string>
d('1') // compile error: string is not a number
d.flush() // type: string | undefined
const s = debounceAsync(async (q: string) => [q], 100)
await s('x') // type: string[]API
debounce(fn, wait?, options?)
function debounce<F extends (...args: any[]) => any>(
fn: F,
wait?: number, // default 0
options?: DebounceOptions,
): Debounced<F>Returns a function that delays calling fn until wait ms have passed since the last call. When fn runs, it gets the arguments and this of the latest call. The debounced function returns the result of the most recent run of fn (undefined until fn has run once).
| Option | Type | Default | Description |
|---|---|---|---|
| leading | boolean | false | Call fn on the first call of a burst. |
| trailing | boolean | true | Call fn after wait ms without calls. If leading is also true, this only happens when there was more than one call in the burst. |
| maxWait | number | none | During a long burst, call fn at least once every maxWait ms. If it is smaller than wait, wait is used. |
| signal | AbortSignal | none | When it aborts, drop any scheduled call and make later calls do nothing. |
throttle(fn, wait?, options?)
function throttle<F extends (...args: any[]) => any>(
fn: F,
wait?: number, // default 0
options?: ThrottleOptions,
): Debounced<F>Returns a function that calls fn at most once every wait ms. The first call runs right away. Calls during the wait are merged into one more call at the end, with the latest arguments.
| Option | Type | Default | Description |
|---|---|---|---|
| leading | boolean | true | Call fn right away on the first call. |
| trailing | boolean | true | Call fn once more at the end of the wait, if there were calls during it. |
| signal | AbortSignal | none | When it aborts, drop any scheduled call and make later calls do nothing. |
Methods of the returned function
Every function returned by debounce, throttle, debounceAsync and throttleAsync has these methods:
| Method | Returns | Description |
|---|---|---|
| cancel() | void | Drops the scheduled call and resets, so the next call starts a new burst. |
| flush() | latest result | Runs the scheduled call now, if there is one. Returns the latest result. |
| pending() | boolean | true if a call to fn is scheduled, so flush() would call fn. |
For debounceAsync and throttleAsync, flush() returns a promise, and cancel(reason?) also rejects the waiting promises (see below).
debounceAsync(fn, wait?, options?) and throttleAsync(fn, wait?, options?)
function debounceAsync<F extends (...args: any[]) => any>(
fn: F,
wait?: number, // default 0
options?: DebounceOptions,
): DebouncedAsync<F>
function throttleAsync<F extends (...args: any[]) => any>(
fn: F,
wait?: number, // default 0
options?: ThrottleOptions,
): DebouncedAsync<F>Same timing and options as debounce and throttle. The difference: every call returns a promise for the result of the run of fn that covers it. All calls merged into one run of fn share one promise.
fncan be sync or async. If it throws or rejects, all the merged calls reject.- Calls that will never run
fn(for example withtrailing: false) resolve right away with the latest result. cancel(reason?)rejects the waiting calls withreason, or with aCancelErrorif you pass no reason.- When
signalaborts, the waiting calls and all later calls reject withsignal.reason. - Promises rejected by
cancel()orsignalnever cause "unhandled rejection" warnings if you ignore them.awaitstill sees the rejection. flush()returns a promise for the latest result.leadingandtrailingcannot both befalse, because the promises would never settle. This throws aTypeError.
CancelError
class CancelError extends Error {
constructor(message?: string) // default message: 'calmfn: cancelled'
}The error that waiting debounceAsync and throttleAsync promises reject with after cancel() with no reason. Its name is 'CancelError'.
Errors
| Error | When |
|---|---|
| TypeError | fn is not a function. |
| RangeError | wait or maxWait is negative, NaN, Infinity or not a number. |
| TypeError | signal is not an AbortSignal. |
| TypeError | debounceAsync or throttleAsync with both leading and trailing set to false. |
Types
These types are exported:
Debounced<F>: the function returned bydebounceandthrottle.DebouncedAsync<F>: the function returned bydebounceAsyncandthrottleAsync.DebounceOptionsandThrottleOptions: the option objects.
Comparison
| | lodash.debounce / lodash.throttle | throttle-debounce | calmfn |
|---|---|---|---|
| leading / trailing | Yes | Yes (noLeading, noTrailing, atBegin) | Yes |
| maxWait | Yes | No | Yes |
| cancel() | Yes | Yes | Yes |
| flush() | Yes | No | Yes |
| pending() | No | No | Yes |
| Returns the latest result | Yes | No | Yes |
| Promise version (await the result) | No | No | Yes (debounceAsync, throttleAsync) |
| AbortSignal | No | No | Yes |
| Throttle never runs twice within wait | No (see below) | Yes | Yes |
| TypeScript types included | No (@types/...) | No (@types/...) | Yes, keeps parameters and this |
| ESM | No (CommonJS only, or all of lodash-es) | Yes | Yes |
| Last published | 2016 | 2022 | New |
Migrating from lodash
Before:
import debounce from 'lodash.debounce'
import throttle from 'lodash.throttle'After:
import { debounce, throttle } from 'calmfn'The calls and options stay the same. calmfn follows the lodash algorithm, including maxWait, the leading and trailing rules, returning the latest result, and passing the latest this and arguments. It differs in these points:
- Throttle never calls
fntwice withinwait. In lodash, a call that comes just after a trailing call runs right away, sofncan run twice a few ms apart.calmfnschedules it forwaitms after the previous run instead. After a long enough pause, the first call still runs right away. pending()exists. lodash 4 has no such method. It means "a call is scheduled".- Invalid input throws. A
waitormaxWaitthat is negative,NaN,Infinityor not a number throws aRangeError. lodash treats it as0. maxWait: undefinedmeans nomaxWait. lodash treats amaxWaitkey that is present butundefinedasmaxWait: wait.- Extras: the
signaloption,debounceAsyncandthrottleAsync.
Notes and limitations
- Async calls are not queued. If
fnis still running when the next call is due, both runs happen at the same time. - With
debounceAsyncandthrottleAsync,leadingandtrailingcannot both befalse. This throws aTypeError. - After
signalaborts, the function stays off. Later calls do nothing (the async versions reject). Create a new function if you need it again. - Throttle timing differs from lodash in one case. See Migrating from lodash.
Requirements
- Node.js 20 or newer. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
