Debounce Implementation

Delay function execution until after a pause in calls.

Code

JavaScript
function debounce(fn, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

const debouncedSearch = debounce((q) => console.log("Search:", q), 300);
debouncedSearch("a");
debouncedSearch("ab");
debouncedSearch("abc");  // Only this runs after 300ms

Line-by-line explanation

Expected output

Search: abc

Related snippets