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 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 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 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
.
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:
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!
Subscribe to receive new article notifications
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.
Comments (0)