Implement a debounce function

MediumTechnical
AppleSenior Software Engineer
267

Write a debounce function that delays invoking a function until after a specified wait time has elapsed since the last time it was invoked.

2 Answers

189
Top Answer

Classic debounce implementation:

function debounce(func, wait) {
  let timeoutId = null;

  return function(...args) {
    // Clear previous timer
    clearTimeout(timeoutId);

    // Set new timer
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

// Usage
const debouncedSearch = debounce((query) => {
  console.log('Searching for:', query);
}, 300);

input.addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

The function only executes after the user stops typing for 300ms.

UtilityMaster
87

TypeScript version with leading/trailing options:

function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  options: { leading?: boolean; trailing?: boolean } = {}
) {
  let timeoutId: ReturnType<typeof setTimeout> | null = null;
  let lastArgs: Parameters<T> | null = null;
  const { leading = false, trailing = true } = options;

  return function(this: any, ...args: Parameters<T>) {
    const shouldCallNow = leading && !timeoutId;
    lastArgs = args;

    clearTimeout(timeoutId!);

    timeoutId = setTimeout(() => {
      timeoutId = null;
      if (trailing && lastArgs) {
        func.apply(this, lastArgs);
      }
    }, wait);

    if (shouldCallNow) {
      func.apply(this, args);
    }
  };
}
  • leading: true - Call immediately on first trigger
  • trailing: true - Call after wait period (default)
TypeScriptNinja

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Apple

View all