TypeScript Debounce Function
When creating a debounce
function in TypeScript, it’s essential to handle type safety, particularly for the callback function's arguments and return type, as well as to ensure compatibility with both synchronous and asynchronous functions. Below is a simple, generic debounce
implementation.
TypeScript Debounce Function
This debounce
function takes a callback
function and a wait time in milliseconds. It creates a timer that resets with each new call, only executing the callback
function once no calls have been made for the duration of wait
.
1 export function debounce<T extends unknown[], U>(2 callback: (...args: T) => PromiseLike<U> | U,3 wait: number4 ) {5 let timer: ReturnType<typeof setTimeout> | undefined;67 return (...args: T): Promise<U> => {8 if (timer) clearTimeout(timer);910 return new Promise((resolve) => {11 timer = setTimeout(() => resolve(callback(...args)), wait);12 });13 };14 }
Explanation of the Code
Generics (T
and U
):
T
is an array of argument types that callback can take.U
is the return type ofcallback
, which can either be a direct value or aPromise
(handled asynchronously).
Timer Management:
timer
is a reference to the current timeout. UsingReturnType<typeof setTimeout>
ensures compatibility with both Node.js and browser environments.clearTimeout(timer)
cancels any active timeout, preventing thecallback
from firing until the debounce period (wait
) has passed without additional calls.
Asynchronous Callback Support:
- The function supports asynchronous callbacks using
await
to handle any promises thatcallback
may return, providing more flexibility.
Usage Example
Here’s how to use this debounce function to limit the frequency of a function that logs data to the console:
1 const logInput = debounce((input: string) => {2 console.log(`User typed: ${input}`);3 }, 300);45 logInput("Hello"); // Only logs if no further calls are made within 300ms
Advantages
- Type Safety: Ensures that the arguments and return types are correctly typed for TypeScript.
- Asynchronous Handling: Supports promises, making it adaptable for various use cases.
This implementation of debounce
can help you efficiently handle performance-intensive operations by reducing the rate at which a function executes while maintaining TypeScript’s type safety and compatibility.