Debounce provides a utility function for delaying function calls until a set time elapses after the last invocation. It prevents excessive function executions during rapid events like user input, window resizing, or API requests.
npm install debounceimport debounce from "debounce";For CommonJS:
const debounce = require("debounce");Named import (also available):
import { debounce } from "debounce";
// or
const { debounce } = require("debounce");import debounce from "debounce";
function resize() {
console.log('height', window.innerHeight);
console.log('width', window.innerWidth);
}
// Debounce the resize function with 200ms delay
window.onresize = debounce(resize, 200);
// Check if execution is pending
console.log(window.onresize.isPending); // boolean
// Cancel any scheduled executions
window.onresize.clear();
// Execute immediately if scheduled and clear timer
window.onresize.flush();
// Execute immediately and clear timer
window.onresize.trigger();Creates a debounced function that delays execution until wait milliseconds have passed since its last invocation.
/**
* Creates a debounced function that delays execution until wait milliseconds have passed
* @param function_ - The function to debounce
* @param wait - Milliseconds to delay (default: 100)
* @param options - Configuration options
* @returns Debounced function with control methods
*/
function debounce<F extends AnyFunction>(
function_: F,
wait?: number,
options?: { immediate: boolean }
): DebouncedFunction<F>;
type AnyFunction = (...arguments_: readonly any[]) => unknown;
type DebouncedFunction<F extends AnyFunction> = {
(...arguments_: Parameters<F>): ReturnType<F> | undefined;
readonly isPending: boolean;
clear(): void;
flush(): void;
trigger(): void;
};Note: A boolean value for options is also supported (deprecated) where true is equivalent to { immediate: true }.
Returns a debounced function that:
undefined if not yet executedisPending (readonly boolean): Indicates whether the debounce delay is currently active.
clear(): Cancels any scheduled executions without executing the function.
flush(): If an execution is scheduled, immediately executes the function and clears the timer. Does nothing if no execution is scheduled.
trigger(): Executes the function immediately and clears the timer if it was previously set.
Basic debouncing:
import debounce from "debounce";
const search = debounce((query) => {
console.log('Searching for:', query);
}, 300);
// Only the last call will execute after 300ms of inactivity
search('a');
search('ap');
search('app');
search('apple'); // Only this will executeImmediate execution mode:
import debounce from "debounce";
const saveData = debounce((data) => {
console.log('Saving:', data);
}, 1000, { immediate: true });
// Executes immediately on first call, then debounces subsequent calls
saveData('data1'); // Executes immediately
saveData('data2'); // Ignored (within debounce period)
saveData('data3'); // Ignored (within debounce period)
// After 1000ms of inactivity, ready for immediate execution againUsing control methods:
import debounce from "debounce";
const processInput = debounce((input) => {
console.log('Processing:', input);
}, 500);
processInput('test');
// Check if execution is pending
if (processInput.isPending) {
console.log('Execution is scheduled');
}
// Cancel the scheduled execution
processInput.clear();
// Or force immediate execution
processInput('urgent');
processInput.trigger(); // Execute immediatelyContext preservation:
import debounce from "debounce";
class DataProcessor {
constructor(name) {
this.name = name;
this.process = debounce(this.process.bind(this), 200);
}
process(data) {
console.log(`${this.name} processing:`, data);
}
}
const processor = new DataProcessor('Main');
processor.process('data'); // Context (this.name) is preservedThe debounce function throws errors in the following cases:
import debounce from "debounce";
// TypeError: Expected the first parameter to be a function
const invalid1 = debounce("not a function", 100);
// RangeError: `wait` must not be negative
const invalid2 = debounce(() => {}, -100);