Course contentsShow
← JavaScript
Lesson 2385 of 2,72349. Common Patterns and IdiomsFree lesson

Leading vs Trailing Edge Debounce

Learn the difference between firing on the first call versus after the pause completes.

Leading vs Trailing Edge Debounce

You'll learn the difference between firing a debounced function on the first call versus after the pause completes.

When you debounce a function, you have two timing options: leading edge (also called "immediate") and trailing edge (the default).

Trailing Edge (Default)

This is what you've been using: the function fires after the user stops triggering events. Think of it like waiting for someone to finish knocking on a door before you answer. If they keep knocking, you keep waiting.

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const search = debounce(() => console.log('Search!'), 500);
// Type... type... type... [500ms pause] → "Search!" logged

Leading Edge

The function fires immediately on the first call, then ignores subsequent calls until the delay passes. It's like answering the door on the first knock, then ignoring further knocks for a few seconds.

function debounceLeading(fn, delay) {
  let timer;
  return function(...args) {
    const callNow = !timer; // true only if timer doesn't exist
    clearTimeout(timer);
    timer = setTimeout(() => timer = null, delay);
    if (callNow) fn(...args);
  };
}

const submit = debounceLeading(() => console.log('Submitted!'), 1000);
// Click → "Submitted!" (immediately)
// Click again within 1s → nothing
// Wait 1s, click → "Submitted!" again

When to Use Each

  • Trailing: Search boxes, window resize handlers, autosave — you care about the final state
  • Leading: Button clicks, game controls — you want instant feedback but prevent spamming

Key Takeaway: Trailing edge debounce waits for silence before firing; leading edge fires immediately then blocks repeats for a cooldown period. Choose based on whether you need the first action or the last state.