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
  • A library brings a lot of motion effects to your website: animejs.com

    Go check it out, scroll a bit and your eyes will be dazzled 😵‍💫

    » Read more
  • A repository that compiles a list of system prompts that have been "leaked" on the Internet. Very useful for anyone researching how to write system prompts. I must say they are quite meticulous 😅

    jujumilk3/leaked-system-prompts

    » Read more
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

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