JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
Prev

Learn the concept

Debouncing & Throttling

performance
mid
optimization

What is the difference between debouncing and throttling?

debounce
throttle
performance
events
optimization
Quick Answer

Debouncing waits until activity stops before executing (e.g., search after user stops typing). Throttling limits execution to once per interval during continuous activity (e.g., scroll events). Both reduce excessive function calls.

Detailed Explanation

Debouncing:

  • Waits for pause in activity
  • Resets timer on each call
  • Executes once after delay
  • Use for: Search inputs, resize end

Throttling:

  • Executes at regular intervals
  • During continuous activity
  • Maximum once per interval
  • Use for: Scroll, mouse move

Key Difference:

  • Debounce: "Wait until they stop"
  • Throttle: "Do it, but not too often"

Code Examples

Debounce implementation and usageJavaScript
// Debounce implementation
function debounce(func, wait) {
  let timeoutId;
  
  return function executedFunction(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), wait);
  };
}

// Usage: Search input
const searchInput = document.getElementById('search');

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

searchInput.addEventListener('input', (e) => {
  search(e.target.value);
});
// User types: h-e-l-l-o
// Only ONE search after user stops (300ms pause)

// React hook version
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// Usage in React
function Search() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 300);

  useEffect(() => {
    if (debouncedQuery) {
      fetchResults(debouncedQuery);
    }
  }, [debouncedQuery]);

  return <input value={query} onChange={e => setQuery(e.target.value)} />;
}

Real-World Applications

Use Cases

Optimizing a search bar or autocomplete input field

By debouncing the input event, API calls are only made after the user stops typing for a short period, reducing unnecessary requests and server load.

Improving performance of a real-time analytics dashboard

By throttling updates to charts or graphs that respond to continuous data streams (e.g., websocket events), ensuring that UI updates occur at a manageable rate and maintain responsiveness.

Handling window resize events for responsive layouts

By debouncing the resize event, complex layout recalculations are only performed once the user finishes resizing the window, preventing janky performance during the resize operation.

Mini Projects

Debounced Search Input

beginner

Implement a search input field that uses a debounce function to delay API calls until the user has paused typing.

Throttled Scroll Progress Bar

intermediate

Create a scroll-triggered progress bar or parallax effect that updates its position/animation using a throttled scroll event listener to maintain smooth performance.

Industry Examples

Google Search

Google's search bar utilizes debouncing to efficiently handle user input, triggering search suggestions or results only after a brief pause in typing, optimizing API usage and responsiveness.

Twitter

Twitter employs throttling for various interactive elements, such as updating the 'like' count or refreshing timelines, to manage network requests and UI rendering efficiently during continuous user activity (e.g., rapid scrolling).

Resources

CSS Tricks - Debouncing and Throttling

article

Related Questions

What are common React performance optimization techniques?

mid
react
Previous
What is the difference between SSR, SSG, and CSR?
Prev