Skip to content

debounce()

Eugene Lazutkin edited this page Feb 25, 2026 · 6 revisions

Description

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.

Key features

  • 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.

Technical specifications

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.

Usage Instructions

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.

Troubleshooting

  • 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.

See Also

Clone this wiki locally