JavaScript patterns: Throttle and Debounce

JavaScript patterns: Throttle and Debounce

In this article, we’ll cover two JavaScript patterns to control the repeated call of event handlers: throttle and debounce.

Do you need to handle a specific event, but you want to control how many times your handler will be called in a given period of time? This is a very common problem and often happens when listening to events such as scroll, mousemove or resize, which are triggered dozens of times a second. But sometimes it’s desirable even for less “frenetic” events, like, for example, to limit an action that occurs when a certain button is clicked.

The example app

In order to understand both patterns, we will use a simple example application that shows the current mouse coordinates in the screen and how many times these coordinates were updated. By looking at this counter, you will find it easier to compare how these two techniques can control the calling of an event handler. This is our app without any event control technique applied:

render();

document.body.addEventListener('mousemove', logMousePosition);

let callsCount = 0;
const positionsEl = document.querySelector('.app__positions');
function logMousePosition(e) {
  callsCount++;
  positionsEl.innerHTML = `
    X: ${e.clientX},
    Y: ${e.clientY},
    calls: ${callsCount}
  `;
}

function render() {
  document.querySelector('#app').innerHTML = `
    # Mouse position (Without event control)



  `;
}

And here is how this initial version of our app behaves:

JavaScript patterns

Full example.

Did you notice the calls count? In just 7 seconds, the logMousePosition function was called 320 times! Sometimes you don’t want a given event handler to be called so many times in a period of time so short. Now, let’s see how to solve this issue.

Throttle

The throttle pattern limits the maximum number of times a given event handler can be called over time. It lets the handler be called periodically, at specified intervals, ignoring every call that occurs before this wait period is over. This technique is commonly used to control scrolling, resizing and mouse-related events.

We need to adapt the example app to use the throttle pattern. In order to do so, let’s change the addEventListener call of the original code to include the throttling logic:

let enableCall = true;
document.body.addEventListener('mousemove', e => {
  if (!enableCall) return;

  enableCall = false;
  logMousePosition(e);
  setTimeout(() => enableCall = true, 300);
});

In the above code:

  1. We’re declaring a enableCall variable to control if the throttling interval is already over. This flag is initially set to true, in order to allow the handler to be called the first time.
  2. Every time a mousemove event is triggered, we test if the enableCall variable is true. If not, that means that the minimum wait period is not over yet and we won’t call the event handler that time.
  3. However, if the enableCall variable is true, we can execute the event handler normally. However, before doing so, we need to set our control flag to false in order to prevent the handler to be called again during the wait interval.
  4. After calling the event handler, we use the setTimeout function to set our flag back to true after 300 milliseconds. This way, our handler will only be authorized to run again when this minimum interval is over.

Full example.

Now, let’s see how the app behaves after applying this technique:

JavaScript patterns

The throttling logic works perfectly! Now, there’s a minimum interval of 300 milliseconds between the updates, drastically reducing our calls count.

A reusable throttle function

In order to make this code reusable, let’s extract it to a separate function:

document.body.addEventListener('mousemove', throttle(logMousePosition, 300));

function throttle(callback, interval) {
  let enableCall = true;

  return function(...args) {
    if (!enableCall) return;

    enableCall = false;
    callback.apply(this, args);
    setTimeout(() => enableCall = true, interval);
  }
}

The logic here is the same as above. When called, the throttle function returns a new event listener. In this version, we’re using a common function in order to preserve the original this context and apply it to the passed callback.

Full example.

Debounce

The debounce pattern allows you to control events being triggered successively and, if the interval between two sequential occurrences is less than a certain amount of time (e.g. one second), it completely ignores the first one. This process is repeated until it finds a pause greater than or equal to the desired minimum interval. Once it happens, only the last occurrence of the event before the pause will be considered, ignoring all the previous ones. A common use case for this pattern is to limit requests in a search box component that suggests topics while the user is typing.

Let’s adapt our example app to use the debounce pattern:

let debounceTimeoutId;
document.body.addEventListener('mousemove', (e) => {
  clearTimeout(debounceTimeoutId);
  debounceTimeoutId = setTimeout(() => logMousePosition(e), 300);
});

The above piece of code contains the essence of the debounce pattern. Every time the event we want to control is fired, we schedule a call to the handler for 300 milliseconds later (by using setTimeout) and cancel the previous scheduling (with clearTimeout). This way, we’re constantly delaying the execution of the handler function until the interval between two sequential events is equal to or greater than a given threshold time.

To sum up:

Let’s say we have a given event being triggered two times (A and B) and there’s an X interval between these two occurrences. If we want to control this event by applying a debounce of Y milliseconds, here’s how it will work:

  • If X < Y, the A call will be ignored.
  • If X >= Y, the B call is considered.
  • In both cases, if the new interval after B is greater than or equal to Y, B will be considered too.

Now, let’s see how it behaves in practice:

JavaScript patterns

Full example

A reusable debounce function

Finally, we can extract the pattern logic to a reusable function. This way, we can easily apply it in similar situations in the future:

document.body.addEventListener('mousemove', debounce(logMousePosition, 300));
function debounce(callback, interval) {
  let debounceTimeoutId;

  return function(...args) {
    clearTimeout(debounceTimeoutId);
    debounceTimeoutId = setTimeout(() => callback.apply(this, args), interval);
  };
}

Full example

Conclusion

  • The debounce pattern delays the calling of the event handler until a pause happens. This technique is commonly used in search boxes with a suggest drop-down list. By applying this pattern, we can prevent unnecessary requests to the backend while the user is typing.
  • The throttle pattern is more suitable for events that are triggered many times in a short period of time. This technique is normally used to control scrolling, resizing and mouse-related events. By using throttle, we can filter repeated executions of an event handler, enforcing a minimum wait time between calls.

javascript design-pattern

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Deep Dive Into Design Patterns With JavaScript. The Builder Pattern

The builder design pattern allows for the creation of a complex object in a procedural manner. Imagine a scenario where you’re creating an application that allows the user to build their own house. Since you want your users to like your product, you provide them a tremendous amount of options. They can add pools, gardens, internet, walls, and even a roof (imagine that, a real roof!). There are several ways to approach this from a code perspective.

JavaScript Design Patterns

A pattern describes a Challange that happens over and another time in the environment, so describes the core of the answer thereto challenge, in such how that you simply will use this resolution a Tillion times over, without doing the same things twice.In application development,it is important to focus on the strategy of constructing, associating application in a very healthy, very strong, and easily maintainable approach, patterns offer a way of giving names to solutions for common challenges.

JavaScript Design Patterns - Command Pattern

JavaScript Design Patterns - Command Pattern. Command pattern is a data driven design pattern and falls under behavioral pattern category. What's the command pattern. Why the command pattern is important. How to implement the command pattern in JavaScript. When to use the command pattern. The idea of the command pattern is to create an abstraction between the operations an object can do, its commands, and the actual commands themselves

JavaScript Design Patterns: The Adapter Pattern

This time we are going to dive into Adapter pattern. Which is one of the simplest but really powerful and underestimated patterns out-there. What is a Design Pattern? Adapter pattern in JavaScript: Adapter is a structural design pattern so it can improve quality and scalability of your code, massively

JavaScript Design Patterns: The Factory Pattern

Lets make it not boring. Explaining Factory Pattern with simple words. We are going to dive into Factory Pattern and how to make use of it in JavaScript.