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

Implementing a Simple Debounce

Write a basic debounce function that delays execution until a pause in events occurs.

Implementing a Simple Debounce

You'll learn how to write a basic debounce function that delays execution until a pause in rapid-fire events.

Now that you understand what debounce solves (preventing function spam during rapid events like typing or scrolling), let's build one from scratch.

The core mechanic is simple: each time the debounced function is called, cancel any pending execution and schedule a new one after a delay. If calls keep coming, the timer keeps resetting. Only when calls stop does the function finally run.

The Basic Implementation

function debounce(func, delay) {
  let timeoutId;
  
  return function(...args) {
    clearTimeout(timeoutId);  // Cancel previous timer
    
    timeoutId = setTimeout(() => {
      func(...args);  // Execute after delay
    }, delay);
  };
}

How It Works

  1. debounce returns a new wrapper function
  2. Each call to the wrapper clears the previous setTimeout with clearTimeout
  3. A fresh timer is started with setTimeout
  4. If no new call happens within delay milliseconds, func finally executes

Using It

const saveInput = (value) => {
  console.log('Saving:', value);
};

const debouncedSave = debounce(saveInput, 500);

// Simulate rapid typing
debouncedSave('H');
debouncedSave('He');
debouncedSave('Hel');
debouncedSave('Hell');
debouncedSave('Hello');  // Only this triggers saveInput after 500ms pause

The function only executes once, 500ms after the last call. Perfect for search boxes or resize handlers!

Key Takeaway: A basic debounce uses setTimeout and clearTimeout to ensure a function only runs after a specified quiet period, resetting the timer on each call.