0
0
JavascriptConceptBeginner · 3 min read

What is Debounce Function in JavaScript: Explanation and Example

A debounce function in JavaScript limits how often a function can run by delaying its execution until a certain time has passed without it being called again. It helps prevent a function from running too many times in quick succession, like when typing or resizing a window.
⚙️

How It Works

Imagine you have a button that you can press many times quickly. Without control, the action behind the button runs every time you press it, which can be too much. A debounce function acts like a timer that waits for you to stop pressing the button for a little while before running the action once.

In JavaScript, debounce works by setting a timer each time the function is called. If the function is called again before the timer ends, the timer resets. Only when the timer finishes without interruption does the function actually run. This way, it groups many quick calls into one.

💻

Example

This example shows a debounce function that delays logging a message until 500 milliseconds have passed without new calls.

javascript
function debounce(func, delay) {
  let timerId;
  return function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

const logMessage = () => console.log('Function executed!');
const debouncedLog = debounce(logMessage, 500);

// Simulate rapid calls
debouncedLog();
debouncedLog();
debouncedLog();

// Only one 'Function executed!' will print after 500ms
Output
Function executed!
🎯

When to Use

Use debounce when you want to limit how often a function runs during rapid events. For example:

  • Typing in a search box: wait until the user stops typing before searching.
  • Window resizing: run layout adjustments only after resizing stops.
  • Button clicks: prevent multiple clicks from triggering repeated actions.

This improves performance and user experience by avoiding unnecessary work.

Key Points

  • Debounce delays function execution until calls stop for a set time.
  • It helps reduce excessive function calls from rapid events.
  • Commonly used in input handling, resizing, and click events.
  • Implemented by resetting a timer on each call.

Key Takeaways

Debounce limits how often a function runs by delaying execution until calls stop.
It improves performance by grouping rapid calls into one action.
Use debounce for events like typing, resizing, and clicking.
Debounce works by resetting a timer on each function call.
Only the last call after the delay triggers the function.