Implement a debounce function. This is a function that limits how often another function can be called.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Logic/Approach:

Debouncing ensures a function is only called after a certain amount of time has passed without it being called again.

1. Return a new function that wraps the original function.

2. Maintain a timeoutId variable in the closure.

3. When the debounced function is called, clear the previous timeout.

4. Set a new timeout that will execute the original function after the specified delay.

function debounce(func, delay) {
  let timeoutId;

  return function(...args) {
    const context = this; // Capture 'this' context

    // Clear any existing timeout
    clearTimeout(timeoutId);

    // Set a new timeout
    timeoutId = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

// Example usage:
function handleInput(event) {
  console.log('Searching for:', event.target.value);
}

const debouncedHandleInput = debounce(handleInput, 300);

// Attach to an input field:
// <input oninput="debouncedHandleInput(event)" />