Create Debounce Function

Question

Create a debounce function that delays the execution of a function until a certain amount of time has passed after the last event trigger.

Coding Answer

function debounce(fn, delay) {
  let timer;

  return function (...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

// Example
function searchData() {
  console.log("Searching...");
}

const debounceSearch = debounce(searchData, 1000);

// Simulate typing
debounceSearch();
debounceSearch();
debounceSearch();

Preview

Searching...

// Printed only once after 1 second

Explanation

  • Debouncing delays function execution
  • clearTimeout() removes previous timer
  • setTimeout() creates new delay
  • Function runs only after user stops triggering events
  • Commonly used in search bars and resize events