Debouncing and Throttling in JavaScript

In the world of JavaScript development, two essential concepts debouncing and throttling play a crucial role in optimizing performance and enhancing user experience. Whether you’re a beginner or an experienced developer, understanding these concepts is vital for writing efficient and responsive JavaScript code.

In this post, we’ll dive deeper into debouncing and throttling, explore their differences, and provide practical examples to help you.

What is Debouncing?

Debouncing is a technique used to ensure that a particular function is executed only after a specified period of inactivity. Imagine a scenario where a user interacts with a search input field, and you want to trigger an API request to fetch search results. Without debouncing, each keystroke would initiate an API call, potentially overwhelming the server and causing performance issues. Debouncing solves this problem by postponing the execution of the function until the user stops typing.

However, with Debounce you can save some API calls and reduce the load on the server or save some money if you are using third-party APIs.

Let’s say you have an input field for searching for products on an e-commerce website. As the user types in the search box, you can debounce the search function to wait for a brief moment of inactivity before sending the request. Here’s how you can achieve this using JavaScript:

// Debounce function
function debounce(func, delay) {
    let timerId;
    return function (...args) {
        clearTimeout(timerId);
            timerId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

function searchProducts(query) {
    // API call to fetch search results
}

const debouncedSearch = debounce(searchProducts, 300);

document.getElementById('searchInput').addEventListener('keyup', function (event) {
    debouncedSearch(event.target.value);
});

In the above example, the debounce function takes a func parameter that represents the function to debounce and a delay parameter that indicates the period of inactivity before executing the function. We create the debouncedSearch function by passing the searchProducts function and setting a delay of 300 milliseconds.

The event listener listens for key-up events on the search input field. It calls debouncedSearch to send the API request only after the user pauses typing for 300 milliseconds.

What is Throttling?

Throttling, similar to debouncing, limits how often you can invoke a function. Unlike debouncing, it executes the function at regular intervals, no matter how frequently the event occurs.

This is useful when you want to limit how often a function runs. Examples include handling scroll events or button clicks.

Suppose you have a button that triggers an animation on a web page. You want to limit how often the animation can be triggered. You can implement throttling to control the execution rate. Here’s an example of how to achieve this using JavaScript:

function throttle(func, delay) {
  let throttled = false;
  return function (...args) {
    if (!throttled) {
      throttled = true;
      func.apply(this, args);
      setTimeout(() => {
        throttled = false;
      }, delay);
    }
  };
}

function animate() {
  // Code to animate elements
}

const throttledAnimation = throttle(animate, 500);

document.getElementById('animateButton').addEventListener('click', throttledAnimation);

In the above example, the throttle function takes the same parameter as debounce but delay represents indicating the minimum time gap required between function invocations. Other things work the same for both concepts.

Conclusion

Debouncing and throttling are powerful techniques that control how often functions run in JavaScript. Using them correctly helps optimize your app’s performance and ensures a smooth, responsive user experience.

For better page speed and performance, see jQuery Lazy Load Plugin to load images only when they appear on the screen.