#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 17 of 50medium

What are Debounce and Throttle?

Understanding rate-limiting function techniques.

What You'll Learn

  • Difference between debounce and throttle
  • Implementation
  • Use cases

Comparison

TechniqueBehaviorUse Case
DebounceExecute after delay endsSearch input
ThrottleExecute at regular intervalsScroll events

Debounce

Executes function only after a specified delay has passed since the last call.

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

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

// Typing "hello" quickly
search('h');
search('he');
search('hel');
search('hell');
search('hello');
// Only logs: 'Searching: hello' (after 300ms)

Throttle

Executes function at most once per specified time period.

code.jsJavaScript
function throttle(fn, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Usage
const handleScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 100);

window.addEventListener('scroll', handleScroll);
// Logs at most every 100ms while scrolling