DEV Community

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

Posted on

Debouncing and Throttling in JavaScript

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.

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

When should you use debouncing?

Debouncing 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, 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.

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

How does debouncing work?

The way debouncing works is by waiting for a given period of time (known as the "timeout") after the last event before executing the function.

If another event occurs before the timeout has elapsed, the timeout is reset and the function is not executed.

This means that the function will only be executed once the user has stopped interacting with the page for the specified period of time.

Here is a simple example of debouncing a scroll event handler:

var scrollTimeout;

window.addEventListener("scroll", function() {
// clearTimeout(scrollTimeout);
// scrollTimeout = setTimeout(function() {
//   // do something expensive
// }, 250);
}, false);
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a global variable called scrollTimeout.

Whenever the user scrolls, we first clear any existing timeout and then set a new one. The function specified will only be executed if the user has not scrolled for 250 milliseconds.

This ensures that the function is only executed once the user has stopped scrolling.

It is important to note that the function will only be executed once the user has stopped scrolling. If the user scrolls multiple times within the specified period, the function will only be executed once.

This can be useful for things like making Ajax requests, where we only want to make the request once the user has finished scrolling.


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.

When should you use throttling?

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.

How does throttling work?

The way throttling works is by executing a function at a fixed interval.

For example, if we wanted to throttle a scroll event handler so that it is only executed every 100 milliseconds, we would use a setInterval() function:

var scrollInterval;
window.addEventListener("scroll", function() {
// clearInterval(scrollInterval);
// scrollInterval = setInterval(function() {
//   // do something expensive
// }, 100);
}, false);
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a global variable called scrollInterval.

Whenever the user scrolls, we first clear any existing interval and then set a new one. The function specified will be executed every 100 milliseconds.

This ensures that the function is only executed at a throttled rate.

It is important to note that the function will be executed at a fixed interval, regardless of how often the user scrolls.

If the user scrolls multiple times within the specified period, the function will be executed multiple times.

This can be useful for things like making Ajax requests, where we want to make sure that the request is only made once every 100 milliseconds.


Throttling vs debouncing

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

Throttling vs debouncing

In general, debouncing is more commonly used to improve performance, while throttling is more commonly used to ensure that a function is only executed once per interval.


Code examples

Here are some examples of debouncing and throttling in action:

function debounce(func, wait, immediate) {
  var timeout;

  return function () {
    var context = this,
      args = arguments;

    var later = function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;

    clearTimeout(timeout);

    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);
  };
}

Enter fullscreen mode Exit fullscreen mode
function throttle(func, wait, options) {
  var context, args, result;

  var timeout = null;

  var previous = 0;

  if (!options) options = {};

  var later = function () {
    previous = options.leading === false ? 0 : Date.now();

    timeout = null;

    result = func.apply(context, args);

    if (!timeout) context = args = null;
  };

  return function () {
    var now = Date.now();

    if (!previous && options.leading === false) previous = now;

    var remaining = wait - (now - previous);

    context = this;

    args = arguments;

    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }

      previous = now;

      result = func.apply(context, args);

      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }

    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode

Hope this blog helped you understand Debouncing and Throttling. Good Luck 👍

Discussion (0)