
As a web developer, whether back-end or front-end, you’ve probably heard the term Throttle before, right? Simply put, throttle is used to limit the number of hits to an endpoint or application by a single user/client within a certain period. For example, if we want to limit the api/user endpoint to only be accessed 60 times per minute, we can use throttling technology. So, what is debounce?
Debounce literally means to bounce if you translate it with Google Translate, and that’s not far off. Debounce comes from an electronics concept, like a TV remote, where the remote only sends a signal when you’ve actually finished pressing a button. The concept is similar here.
Let me explain. As a good front-end developer, it’s best to maintain harmony between FE and BE developers, right? One way to do this is by using debounce. For example, suppose we want to create an input field that searches for a list of districts based on the keyword entered by the user. So, what should we do? Here’s a sample case.
An input field requires a minimum of 3 characters, and the system should hit the API when the user finishes typing, with a 100ms delay after the last input. So, how do we do this in JavaScript? Here’s how:
var or let, as needed.let debounce
const onChange = () => {
if (debounce) {
clearTimeout(debounce)
}
debounce = setTimeout(() => {
fetch('some_stuff')
}, 100)
}
clearTimeout function to remove the queued delay.fetch (the main function) will automatically be triggered.Short and sweet, right? It's not hard to prevent things like flood caused by front-end apps—just start by using debounce. But that doesn't mean you should ignore throttle; you still need both to keep things in sync. So that's a simple article from me, thanks for reading and see you in the next post.