debounce, throttle, and once - three functions to enhance user logic!

debounce, throttle, and once - three functions to enhance user logic!

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » Read more

Problem

Finding solutions to problems is a crucial skill for programmers. Usually, the more we work, the more experience we gain. At this point, when faced with similar problems, we can quickly find a solution.

There are many ways to learn from experience, one of which is to search and read many articles and documentation online. Sometimes the knowledge we acquire may not be immediately necessary, but it can be useful at some point. Or at least, it stays in our heads and we can think to ourselves, "Oh, so for this case, we should handle it like this...".

debounce, throttle, and once are three utility functions that can be applied in many cases. Especially in UI/UX logic, user experience... In today's article, I would like to present their uses and how to use them.

Debounce

Debounce is a technique that prevents a series of similar events from occurring continuously. Instead, the next event is only triggered after a certain period of inactivity.

One common example we often encounter is the auto-complete feature in a search input field. As we type characters, search results or suggested phrases appear. Behind the scenes, there is some processing happening, such as making an API call to fetch data before the user clicks the search button or presses Enter. If we listen for the keypress event, an API call will be made for every keystroke. This is inefficient because users can type very fast and the entered keyword may not be complete yet. To optimize this, we can wait for a certain period of user inactivity before triggering the API call.

This is where debounce comes in handy. A debounce function may look like this:

function debounce(func, delay) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), delay);
  };
}

Then, we can use this function in the keypress event handler. Here's an example using Vue:

<input @keypress="debounce(triggerCallAPI, 500)" />

In this example, triggerCallAPI will be called only after 500ms of inactivity from the user.

Another common case is handling browser window resizing with the resize event. During window resizing, there might be several functions that need to run to handle logic. If we call these functions continuously on resize, it will definitely affect performance. In this case, we can use debounce to solve this problem.

Throttle

Throttle is somewhat similar to Debounce. It also prevents events from occurring continuously, but in a different way compared to Debounce.

While Debounce triggers the event after a certain period of inactivity, Throttle triggers the event after a certain period of time, regardless of whether the event occurred or not. In other words, Throttle allows running an event only once every x seconds. After x seconds, the next run will be executed if it is still triggered.

A throttle function may look like this:

function throttle(func, delay) {
  let wait = false;

  return (...args) => {
    if (wait) {
        return;
    }

    func(...args);
    wait = true;
    setTimeout(() => {
      wait = false;
    }, delay);
  }
}

Whenever you need to limit the time between event triggers, you can apply Throttle. For example, preventing users from clicking the "Submit" button too quickly.

<input type="submit" @submit="throttle(triggerCallAPI, 500)" />

This means that triggerCallAPI will be called only every 500ms, regardless of how many times the user clicks the button.

Once

Once allows an event to be called only once. Once is useful in cases where you only allow users to perform an action once per session.

A once function may look like this:

function once(func) {
  let ran = false;
  let result;
  return function() {
    if (ran) return result;
    result = func.apply(this, arguments);
    ran = true;
    return result;
  };
}

An example usage is for the "Mark All as Read" button in a notification panel. Users only need to click that button once per session.

<button @click="once(triggerCallAPI)">Mark All as Read</button>

triggerCallAPI will be called only once when the user clicks the button. Subsequent clicks will not trigger triggerCallAPI.

Summary

The above are 3 functions - debounce, throttle, and once - with descriptions and usage examples. They are commonly used in handling user interface logic, to the extent that many utility libraries, such as lodash, include these three functions. Knowing about them and how to use them can help you save time in problem-solving similar cases as mentioned in this article.

References:

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...