⏱️ Debounce & Throttle
jsintermediate

⏱️Debounce & Throttle

Debounce delays execution until inactivity; throttle limits execution rate. Both optimize performance for high-frequency events.

Memory Trick

Debounce = elevator door (waits for last person). Throttle = heartbeat (regular pulse no matter what).

Log in to track your mastery & progress

1️⃣ Definition (WHAT)

  • Debounce: Delays function execution until activity stops for a specified time
  • Throttle: Limits function execution to a fixed rate (once per X ms)
DebounceThrottle
TriggerAfter last event + delayAt regular intervals
UseSearch input, auto-saveScroll, resize tracking
RiskMay feel unresponsiveMay skip intermediate events

2️⃣ How Debounce Works

Resets the timer on every call. Only executes after the delay completes with no new calls.

js
function debounce(fn, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } // Usage const search = debounce((query) => fetchResults(query), 300); input.addEventListener('input', (e) => search(e.target.value));

Key: The timer variable is captured via closure.

3️⃣ How Throttle Works

Executes the function immediately, then ignores calls until the interval expires.

js
function throttle(fn, limit) { let lastRun = 0; return function(...args) { const now = Date.now(); if (now - lastRun >= limit) { lastRun = now; fn.apply(this, args); } }; } // Usage const onScroll = throttle(() => updateProgress(), 100); window.addEventListener('scroll', onScroll);

4️⃣ When to Use Which

ScenarioBest ChoiceReason
Search inputDebounceWait for user to stop typing
Auto-saveDebounceOnly save after editing stops
Window resizeThrottlePeriodic layout recalc
Scroll trackingThrottleSmooth, regular updates
Button spam protectionDebounce or Click LockPrevent duplicate submissions
Animation framesthrottle at 60fpsSync with rendering

Was this helpful?

Test your Knowledge

3 questions to cement what you just learned.