Skip to main content

implementing debounce in javascript with explaination

· 3 min read
Parth Maheta

Debouncing is a technique used in JavaScript to control the rate at which a function is invoked. It ensures that time-consuming tasks do not fire so often, potentially improving performance. In this beginner-friendly guide, we'll explore the concept of debouncing and implement a simple debouncing function.

Understanding Debouncing

Consider a scenario where a user is typing in a search bar, and with each keystroke, an API call is made to fetch search results. Without debouncing, an API call would be triggered for every keystroke, leading to unnecessary requests. Debouncing allows you to delay the invocation of a function until after a certain amount of time has passed since the last invocation.

Implementing Debouncing

Let's create a simple debouncing function in JavaScript. We'll use the setTimeout function to introduce a delay between function invocations.

function debounce(func, delay) {
let timeoutId;

return function (...args) {
// Clear the previous timeout
clearTimeout(timeoutId);

// Set a new timeout
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
}

In this implementation:

  • func is the function we want to debounce.
  • delay is the time (in milliseconds) to wait before invoking the function after the last call.

Using the Debouncing Function

Let's create an example to see the debouncing function in action. Suppose we have a function that logs a message to the console.

function logMessage(message) {
console.log(message);
}

Now, we'll use the debounce function to debounce the logMessage function:

const debouncedLog = debounce(logMessage, 500);

// Usage example: Debounced function for logging messages
debouncedLog("Hello"); // Will not log immediately

// After 500 milliseconds...
debouncedLog("World"); // Will log "World" to the console

In this example, the logMessage function is debounced with a delay of 500 milliseconds. If you call debouncedLog multiple times within that time frame, the actual logging will only occur once, after the delay has passed since the last invocation.

Real-World Example: Debouncing User Input

Let's apply debouncing to a common scenario where a search function is triggered by user input.

// Simulate an API call for search results
function fetchSearchResults(query) {
console.log(`Fetching results for: ${query}`);
// In a real application, this is where you would make an API call
}

// Debounce the search function with a delay of 300 milliseconds
const debouncedSearch = debounce(fetchSearchResults, 300);

// Simulating user input in a search bar
debouncedSearch("React"); // Won't trigger an immediate API call

// After 300 milliseconds...
debouncedSearch("React Hooks"); // Will trigger an API call with the latest query

In this example, the fetchSearchResults function is debounced with a delay of 300 milliseconds. As the user types in a search bar, the actual API call will only be made after the user pauses for 300 milliseconds, preventing unnecessary API requests with each keystroke.

Conclusion

Debouncing is a valuable technique in JavaScript to control the frequency of function invocations, especially in scenarios where you want to optimize performance by delaying the execution of time-consuming tasks. The simple debouncing function introduced in this guide can be adapted and applied to various situations in your web development projects.