Implement debounce

A debounce function is an optimization technique that limits the rate at which an expensive or frequently-occurring function can be executed. They're commonly used for things like:

  • Search Input Autocomplete: To prevent excessive server requests as the user types.
  • Window Resize Handlers: To avoid intensive recalculations on every resize pixel change.
  • Scroll Listeners: To trigger actions only after scrolling pauses.

Implementation

function debounce(callback, delay) {
  let timeoutId;
 
  return function(...args) {
    window.clearTimeout(timeoutId); // Cancel any existing timeout, e.g. the timer counting only start when user stop typing/scrolling.
 
    timeoutId = setTimeout(() => {
      callback.apply(this, args); // Execute the function with its original 'this' and arguments
    }, delay);
  }
}

How It Works:

  1. Closure: The debounce function returns an inner function, forming a closure. This closure holds the timeoutId variable.
  2. Timeout Management: Each time the returned function is called, it clears the previous timeout (if one exists) and sets a new timeout.
  3. Delayed Execution: The originally passed function (callback) is only executed after the delay has elapsed and the user has stopped calling the debounced function.

Example Usage

function handleInputChange() {
  console.log('Fetching suggestions...')
  // Simulate fetching autocomplete suggestions
}
 
const debouncedInputChange = debounce(handleInputChange, 500);
 
inputField.addEventListener('input', debouncedInputChange);
Last Update: 18:03 - 18 April 2024

On this page