DEV Community

Cover image for Debouncing and Throttling in JavaScript
vedanth bora
vedanth bora

Posted on

Debouncing and Throttling in JavaScript

Intro

Debouncing and Throttling are performance optimisation techniques, both of them control how many times we allow a function to be executed over time

What is debouncing ?

Debouncing is an approach to rate-limiting a function in JavaScript. It is a technique that is often used to improve performance, by ensuring that a function is only executed once within a given time period.

It is most commonly used when attaching event handlers to scroll, resize or keypress events.

There are a number of ways to implement debouncing, but the most common is to use a setTimeout() function.

For example, when a user is scrolling through a web page, there is no need to execute a function on every scroll event. Instead, we can debounce the function so that it is only executed once the user has finished scrolling.

Let’s understand this with an example. Let’s say we have a autocomplete search input.

Type in the input to see how many times fetch data is being called.


const input = document.getElementById("input");
const output = document.querySelector(".output");

let counter = 0;

const getData = () => {
  console.log("fetch data");
  counter++;
  output.innerText = "fetch data " + counter++;
};

input.addEventListener("keyup", getData);
Enter fullscreen mode Exit fullscreen mode

We can see that there are too many fetchData calls because the keyup event is fired every time the user types, this results in unnecessary calls to the api. We can solve this problem by using Debouncing. What we want to do is we want the getData function to execute after the user as stopped typing.

Let’s do this by implementing our own debounce function

const myDebounce = (callback, delay = 250) => {
  let timer;

  return (...args) => {
    if(timer) clearTimeout(timer)

    timer = setTimeout(() => {
      callback(...args)
    }, delay)
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we need to pass the getData function as a callback in the myDebounce function we have just written .

const input = document.getElementById("input");
const output = document.querySelector(".output");

let counter = 0;

const getData = () => {
  console.log("fetch data");
  counter++;
  output.innerText = "fetch data " + counter++;
};

const myDebounce = (callback, delay = 250) => {
  let timer;

  return (...args) => {
    if(timer) clearTimeout(timer)

    timer = setTimeout(() => {
      callback(...args)
    }, delay)
  }
}

input.addEventListener("keyup", myDebounce(getData));
Enter fullscreen mode Exit fullscreen mode

You can see the difference in this code pen compared to the one earlier without debouncing.

Lets take a look another example of debouncing on a scroll event, the event is fired 100ms after the user has stopped scrolling

So debouncing is a technique that will executed a function once the user has stopped interacting with the page for the specified period of time.


What is throttling ?

Throttling is a technique for rate-limiting a function in JavaScript. It is similar to debouncing, but instead of waiting for the user to stop interacting with the page, it is executed at a fixed interval.

This interval is known as the "throttle interval".

There are a number of ways to implement throttling, but the most common is to use a setInterval() function.

Throttling is most commonly used when attaching event handlers to scroll, resize or keypress events.

For example, when a user is scrolling through a web page, we may only want to execute a function every 100 milliseconds. This would ensure that the function is not executed on every scroll event, but at a throttled rate.

This can be useful for things like recalculating positions or dimensions, or even making Ajax requests.

Let’s look at the scroll example without throttling. We can see that the event is fired may times in less than one second and this is again an expensive operation and hampers performance. We can solve this using throttling.

The way throttling works is by executing a function at a fixed interval. Let’s write our own throttle function

const myThrottle = (callback, delay = 250) => {
        let last = 0

        return (..args) => {
                let now = new Date().getTime()

                if(now - last < delay) return 

                last = now

                return callback(..args)

        }
}
Enter fullscreen mode Exit fullscreen mode

Now let’s look at the scroll example but with throttling.


Throttling vs debouncing

At first glance, throttling and debouncing may seem like similar techniques. However, there are a few key differences between the two

Debouncing Throttling
Debouncing ensures that a function is only executed once the user has stopped interacting with the page. Throttling ensure a function is executed at a fixed interval.

Top comments (0)