JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Debounce & Throttle

javascript
senior
debounce-throttle

How would you implement a debounce function from scratch with advanced features?

debounce
implementation
closures
this
performance
interview-coding
Quick Answer

A debounce function delays execution until a pause in calls, using a closure to manage a timer that resets on each invocation. Advanced implementations support leading/trailing edge execution, cancel and flush methods, and a maxWait option to guarantee eventual execution.

Detailed Explanation

What is Debouncing:

  • Delays invoking a function until after a specified wait time has elapsed since the last call
  • Commonly used for search inputs, window resize handlers, and form validation
  • Prevents excessive function calls during rapid-fire events

Core Implementation:

  1. Use a closure to store the timer ID, pending arguments, and context
  2. On each call, clear the previous timer and set a new one
  3. Forward this context and arguments to the original function
  4. Return the wrapper function

Advanced Features:

  1. Leading edge: Execute immediately on the first call, then debounce subsequent calls. Useful when you want instant feedback on the first interaction.

  2. Trailing edge: Execute after the wait period (default behavior). Both leading and trailing can be enabled simultaneously.

  3. Cancel: Abort any pending invocation by clearing the timer. Critical for cleanup in component unmount scenarios.

  4. Flush: Immediately invoke the pending function if one exists. Useful for form submission where you need the latest value now.

  5. maxWait: Guarantee the function is called at least once every maxWait milliseconds, even if calls keep coming. Prevents the debounced function from being delayed indefinitely.

Key Interview Points:

  • Proper this binding via .apply() or .call()
  • Argument forwarding with rest/spread
  • Closure for timer state management
  • Return value handling (return a promise or the last result)
  • Memory cleanup to prevent leaks

Code Examples

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

  return function debounced(...args) {
    // Clear any pending timer
    clearTimeout(timeoutId);

    // Set a new timer that calls func after wait ms
    timeoutId = setTimeout(() => {
      func.apply(this, args);
      timeoutId = null;
    }, wait);
  };
}

// Usage
const handleSearch = debounce((query) => {
  console.log('Searching for:', query);
  fetch(`/api/search?q=${query}`);
}, 300);

// Rapid calls — only the last one executes
handleSearch('h');       // cancelled
handleSearch('he');      // cancelled
handleSearch('hel');     // cancelled
handleSearch('hello');   // executes after 300ms

Real-World Applications

Use Cases

Search-As-You-Type

Debouncing search input to avoid firing API requests on every keystroke, waiting until the user pauses typing before querying the server

Window Resize Handler

Debouncing resize event listeners to recalculate layouts only after the user finishes resizing, preventing expensive reflows on every pixel change

Auto-Save in Editors

Debouncing document changes in text editors to save drafts only after the user stops typing, reducing unnecessary write operations and API calls

Mini Projects

Full-Featured Debounce Library

advanced

Implement a complete debounce utility with leading, trailing, maxWait, cancel, flush, and pending methods with comprehensive tests covering edge cases

Autocomplete Search Component

intermediate

Build a React autocomplete input that debounces API requests, shows loading states, handles race conditions with AbortController, and highlights matching text

Industry Examples

Lodash

Provides the most widely-used debounce implementation with leading, trailing, maxWait, cancel, and flush features used across millions of projects

VS Code

Debounces file watching, search indexing, and IntelliSense suggestions to maintain editor responsiveness during rapid typing

Resources

Lodash debounce source code

article

JavaScript.info - Debounce and Throttle

article

Related Questions

How do debounce and throttle work, and when would you use each?

mid
debounce-throttle

What is a closure in JavaScript and why are they useful?

mid
closures
Previous
What is CORS, when do CORS errors occur, and how can they be resolved?
Next
How would you implement a simplified Promise from scratch?
PrevNext