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
  • I got an email from Windsurf today - they said I'm an active user so they're giving me early access to Windsurf Next. What's that?

    It's just the next version of Windsurf, they're improving a lot of things in it. After trying it out for a day, I think the Vietnamese support has gotten better and the suggestions are more accurate now. I'm not sure yet, I'll have to use it more to see, that's my initial impression.

    Oh, I'm still loyal to the free version 😆.

    » Read more
  • One thing I find a bit confusing is that Postman requires an internet connection to function, everyone. This has probably been the case for several years now; back then, many people complained about it, but it’s still the same, still needing the internet to work.

    They must think that IT folks always have internet access, which is why they added the requirement for a network connection just to be safe. Indeed, I am rarely or never affected since I always have internet while working. However, I believe many others find this issue extremely frustrating. Proof of that is that after this incident, quite a few open-source projects have been created to replace Postman.

    Among them, I see the most notable one is hoppscotch. The interface looks quite similar to Postman, but it seems "nicer" 😁

    » Read more
  • Have you ever tried reading the Google Analytics (GA) API documentation? The first time I read it, I was completely lost, not understanding what they were presenting, what the next steps should be... in general, the way it was presented was so convoluted that I couldn’t read it all at once to get immediate results.

    However, if you interact with it more, you'll find that it follows a certain standard. This means that the next time you read it, you'll know what to read first and what to read next, and then move on to the steps to get results, which makes you a bit more proficient. While I was fumbling around with the GA API, I discovered this website that helps me quickly test queries for results, and then I just need to copy the query and put it into the API. Quick and easy! 😅

    GA4 Query Explorer

    » 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...