the time interval in milliseconds for debouncing
the function to be debounced
Optional
rejection_value: REJif a rejection value is provided, then old unresolved pending promises will be rejected with the given value, when a new call to the debounced function is made (within the debouncing waiting period)
a function (that takes arguments intended for fn
) that returns a promise, which is resolved once wait_time_ms
amount of time has passed with no further calls
// assume that `sleep(time_ms: number)` is a function that synchronously creates a delay for `time_ms` number of milliseconds
const fn = (v: number) => {
console.log(v)
return v + 100
}
const debounced_fn = debounce(1000, fn, "SEPPUKU!")
// `a` is a promise that should resolve after 1000ms
const a = debounced_fn(24).catch((reason) => { console.log("they want me to ", reason) })
sleep(500)
// `debounced_fn(42)` rejects `a`'s promise and then returns a new promise (`b`) that will resolve in 1000ms
// when `debounced_fn(42)` is called this quickly, promise `a` is first rejected, which results in immediate logging of `"they want me to SEPPUKU!"` in the console
const b debounced_fn(42)
// then, 1000ms later, you should see "42" in your console (due to promise `b`)
sleep(2000)
c = debounced_fn(99) // Returns a new promise that resolves after 1000ms
// 1000ms later, you should see "99" in your console
Generated using TypeDoc
creates a debounced version of the provided function that returns a new promise.
the debounced function delays the execution of the provided function
fn
until the debouncing intervalwait_time_ms
amount of time has passed without any subsequent calls.if a
rejection_value
is provided, then any subsequent calls to the debounced function that are made within the debouncing interval, will reject the previous promises. thus you will have tocatch
them in that case. (otherwise it will result in an error)you may worry that too many calls to a non-rejectable debounced function (i.e. when
rejection_value === undefined
) will create too many promise objects, possibly resulting in memory leaks. however, luckily, modern javascript engines are not afflicted by too many pending promise objects. in fact, choosing to reject promises (i.e. by settingrejection_value
), might be more expensive down the line, as error catching is typically expensive.also check out debounceAndShare, which avoids this "lots of promise objects" issue by sharing the same promise across all quick callers of the debounce. but it will require careful usage, as all promised callers will eventually get resolved, which may create an unintended avalaunch of subsequent
then
calls if not used carefully.