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 software that converts text to speech created by a Vietnamese programmer - J2TEAM - Text to Speech (Free). You can convert dozens of languages into dozens of different natural voices. The special thing is that it is free.

    In preliminary evaluation, the conversion of long texts or texts in pure Vietnamese is very good. However, when it includes English words, it sounds a bit funny 😅

    » Read more
  • How terrifying, Codeium - known as a competitor to Github Copilot, as it allows users to use it for free without limits. Recently, they introduced the Windsurf Editor - no longer just a VSCode Extension but a full Editor now - directly competing with Cursor. And the main point is that it... is completely free 🫣.

    » Read more
  • There is a rather interesting study that I came across: "Users never bother to read things they don't want to." (That's a bold statement, but it's more true than not. 😅)

    Don't believe it? I bet you've encountered situations where you've clicked on a button repeatedly and it doesn't respond, but in reality, it has displayed an error message somewhere. Or you've filled out everything and then when you hit the submit button, it doesn't go through. Frustrated, you scroll up or down to read and find out... oh, it turns out there's an extra step or two you need to take, right?

    It’s not far from the blog here. I thought that anyone who cares about the blog would click on the "Allow notifications" button just below the post. But the truth is, no one bothers to click it. Is it because they don't want to receive notifications? Probably not! I think it's because they just didn’t read that line.

    The evidence is that only when a notification pops up and takes up half the screen, or suddenly appears to grab attention, do they actually read it—and of course, it attracts a few more subscribers—something that was never achieved before.

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

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)

Leave a comment...