-
-
Notifications
You must be signed in to change notification settings - Fork 0
debounce()
Eugene Lazutkin edited this page Feb 25, 2026
·
6 revisions
The debounce() function is a utility that ensures a function is not called too frequently. It delays the execution of the function until after a specified wait time has elapsed since the last time it was invoked. This is particularly useful in scenarios where a function may be triggered multiple times in quick succession, such as during window resizing or keypress events.
- Delay Execution: The function execution is delayed until after the specified time has passed since the last invocation.
- Single Invocation: Ensures that the function is only called once after the specified delay, even if it is triggered multiple times.
- Flexible Arguments: Supports passing any number of arguments to the debounced function.
debounce() is available as a named and default export.
const debouncedFn = debounce(fn, ms);-
Parameters:
-
fn: The function to debounce. It can have any number of arguments. Its return value will be ignored. -
ms: The number of milliseconds to wait before invoking the function.
-
- Returns: A new function that, when invoked, will delay the execution of the original function.
- TypeScript Support: Includes TypeScript self-types for better integration with TypeScript projects.
To use the debounce() function, import it into your module and wrap the function you want to debounce:
import debounce from 'time-queues/debounce.js';
const log = () => console.log('Function executed!');
const debouncedLog = debounce(log, 300);
// Call the debounced function multiple times
debouncedLog();
debouncedLog();
// Only one "Function executed!" will be logged after 300ms.- Function Not Executing: Ensure that the debounced function is being called correctly and that the wait time (ms) is set appropriately.
- Performance Issues: If the function is still being called too frequently, consider increasing the delay time.
- throttle() - Rate limiting function
- audit() - Execute after delay