Debouncing and Throttling

Debouncing and Throttling are performance optimization techniques used to improve performance of a code that is executed repeatedly within a time frame.

In this post, lets look at these techniques in details and see how it is used to optimize your code.

Debouncing

Debouncing is simply a technique to limit rate at which a function gets invoked.

There are few functionalities in a web app that requires time consuming computation every time it is called, this results in poor performance. So, instead of calling a function on every event change we club it together and fire a single call.

Implementing Debounce

Before moving on to debounce implementation, let's take an example and understand what happens when you don't have debounce implementation.

Here we have a search feature for countries, in case when we do not have debounce you can see that the state is updated on every event change, this makes unnecessary api calls, resulting in poor performance.

On the other hand, when we use debounce the search function is called after the user stops typing and after the specified delay. This reduces the API called made for search, resulting in better performance.

Let's look at the useDebounce custom hook.

  • We pass a value and the delay we need.
  • When this function is called again, we clear the previous timer and reset it to the specified delay.
export const useDebounce = (value, delay) => {
  const [debounceValue, setDebounceValue] = useState(value);

  useEffect(() => {
    const timerId = setTimeout(() => {
      setDebounceValue(value);
    }, delay);
    return () => {
      clearTimeout(timerId);
    };
  }, [value, delay]);

  return debounceValue;
};

Use cases

Here, are few use cases where debounce can help improve the performance of the app

  • Implementing suggestive text, where similar to search we wait for user to stop typing for few seconds and then suggest the text.
  • Content loading for apps where user keeps scrolling, if scroll event is fired frequently, it might impact the performace, so in such cases we apply debouncing on scroll events

Throttling

Throttling or Throttle function is used to call a function after a specific time interval except for the first call which gets executed immediately.

The main difference between throttle and debounce is that throttle gurantees the execuion of the function regularly at a fixed interval.

Implementing Throttle

Let's take a look and understand what happens when we don't use throttle. In this example an event is called everytime a scroll happens, this results into a poor performance and unnecessary api calls.

%[codesandbox.io/embed/without-throttle-lhchv..

Now, let's optimize this using throttle function.

Here, on scroll we call the throttle function with a callback and a delay and it checks if the fixed interval has passed or not and only then it calls the callback function.

const throttleFunction = (callback, delay) => {
  let prev = 0;
  return (...args) => {
    const now = new Date().getTime();
    if (now - prev > delay) {
      prev = now;
      return callback(...args);
    }
  };
};

This, prevents the frequenct calling of the function and makes the website faster.