Files
node/lib/internal/util/debounce.js
James M Snell 67798df884 util: share helpers between debounce() and throttle()
util.debounce() and util.throttle() duplicated the construction of the
AbortError used for cancel()/abort, and the property definitions for
the returned function's control methods, state getters, length, and
name. Move both into internal/util/wrapped_function.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67495
Reviewed-By: Guilherme Araújo <arauujogui@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
2026-11-17 18:37:00 +00:00

225 lines
5.2 KiB
JavaScript

'use strict';
const {
ArrayPrototypePush,
PromiseReject,
PromiseWithResolvers,
ReflectApply,
SymbolDispose,
} = primordials;
const {
AbortError,
} = require('internal/errors');
const {
validateAbortSignal,
validateBoolean,
validateFunction,
validateInteger,
validateObject,
} = require('internal/validators');
const { addAbortListener } = require('internal/events/abort_listener');
const {
createAbortError,
defineWrapperProperties,
} = require('internal/util/wrapped_function');
const { kEmptyObject } = require('internal/util');
const { TIMEOUT_MAX } = require('internal/timers');
const { clearTimeout, setTimeout } = require('timers');
const { markPromiseAsHandled } = internalBinding('util');
/**
* @typedef {object} DebounceOptions
* @property {AbortSignal} [signal] An AbortSignal that cancels pending and future calls.
* @property {boolean} [leading] Whether to invoke on the leading edge.
* @property {boolean} [rejectOnCancel] Whether to reject superseded calls.
*/
/**
* Creates a function that delays calling `fn` until `wait` milliseconds have
* elapsed since its most recent invocation.
* @param {Function} fn
* @param {number} wait
* @param {DebounceOptions} [options]
* @returns {Function}
*/
function debounce(fn, wait, options = kEmptyObject) {
validateFunction(fn, 'fn');
validateInteger(wait, 'wait', 0, TIMEOUT_MAX);
validateObject(options, 'options');
const {
leading = false,
rejectOnCancel = false,
signal,
} = options;
validateBoolean(leading, 'options.leading');
validateBoolean(rejectOnCancel, 'options.rejectOnCancel');
validateAbortSignal(signal, 'options.signal');
if (signal?.aborted) {
throw new AbortError(undefined, { __proto__: null, cause: signal.reason });
}
let args;
let abortError;
let abortListener;
let pendingCalls = [];
let refed = true;
let timeout;
function rejectPending(error) {
const calls = pendingCalls;
pendingCalls = [];
for (let i = 0; i < calls.length; i++) {
calls[i].reject(error);
}
}
function cancelWithError(error) {
if (timeout === undefined) return;
clearTimeout(timeout);
timeout = undefined;
stopListeningForAbort();
args = undefined;
rejectPending(error);
}
function cancel(reason) {
if (timeout === undefined) return;
cancelWithError(createAbortError(reason));
}
function abort() {
if (abortError === undefined) {
abortError = createAbortError(signal.reason);
}
cancelWithError(abortError);
}
function listenForAbort() {
if (signal !== undefined && abortListener === undefined) {
abortListener = addAbortListener(signal, abort);
}
}
function stopListeningForAbort() {
if (abortListener !== undefined) {
abortListener[SymbolDispose]();
abortListener = undefined;
}
}
function ref() {
refed = true;
timeout?.ref();
return debounced;
}
function unref() {
refed = false;
timeout?.unref();
return debounced;
}
function invoke(callArgs, calls) {
if (signal?.aborted) {
abort();
for (let i = 0; i < calls.length; i++) {
calls[i].reject(abortError);
}
return;
}
let result;
try {
result = ReflectApply(fn, debounced, callArgs);
} catch (error) {
for (let i = 0; i < calls.length; i++) {
calls[i].reject(error);
}
return;
}
for (let i = 0; i < calls.length; i++) {
calls[i].resolve(result);
}
}
function invokePending() {
const callArgs = args;
args = undefined;
const calls = pendingCalls;
pendingCalls = [];
if (calls.length !== 0) invoke(callArgs, calls);
}
function onTimeout() {
timeout = undefined;
stopListeningForAbort();
invokePending();
}
function flush() {
if (pendingCalls.length === 0) return;
clearTimeout(timeout);
timeout = undefined;
stopListeningForAbort();
invokePending();
}
function debounced(...callArgs) {
if (signal?.aborted) abort();
if (abortError !== undefined) return PromiseReject(abortError);
const invokeNow = leading && timeout === undefined;
if (timeout !== undefined) {
if (pendingCalls.length !== 0) {
markPromiseAsHandled(pendingCalls[pendingCalls.length - 1].promise);
if (rejectOnCancel) {
rejectPending(new AbortError('The debounced call was superseded'));
}
}
timeout.refresh();
} else {
timeout = setTimeout(onTimeout, wait);
if (!refed) timeout.unref();
listenForAbort();
}
if (signal?.aborted) {
abort();
return PromiseReject(abortError);
}
const call = PromiseWithResolvers();
if (invokeNow) {
invoke(callArgs, [call]);
} else {
ArrayPrototypePush(pendingCalls, call);
args = callArgs;
}
return call.promise;
}
defineWrapperProperties(debounced, fn, {
__proto__: null,
cancel,
flush,
ref,
unref,
}, {
__proto__: null,
pending() {
return pendingCalls.length === 0 ? null : pendingCalls[pendingCalls.length - 1].promise;
},
pendingCount() { return pendingCalls.length; },
});
return debounced;
}
module.exports = debounce;