JavaScript Junkie 1: Implement Debouncing from Scratch

JavaScript Junkie 1: Implement Debouncing from Scratch

This is a weekly blog series where every Sunday, I will try to learn something and post a blog about it.

In this article, I will cover an interesting topic, which is Debouncing. It is a practical solution used in real-world applications to improve performance. Let’s talk more about it.

Debouncing is a technique to limit the rate at which a function is called. This is often useful in situations where a function is called repeatedly, such as when a user is typing in a text input field, and you only want it to be executed once after a certain amount of time has passed since the last call.

One of the common cases of debouncing is the search field of any website. When users type on the search field, not necessarily on every keystroke, it makes an API call. We set a specific timer, and we wait to make a call until the timer finishes. If another call is made during this time, the timer is reset, and the function is not executed until the specified time has passed since the last call.

Let’s take a look at this code:

This is a debounce function. It takes two arguments: func, which is the function to be debounced, and wait or delay, which is the amount of time to wait/delay between calls. First, we are setting the value of this to the global this value, and also setting the args value to the arguments passed in this function. Then we are using setTimeout to execute our function after a certain amount of time. Suppose, we set a timer of 300ms and call this debounce function 5 times in this 300ms. Then on the first call, our function will set a timer. On the second call, as the timer still exists from the first call, we will clear the timer and set a new timer. It will happen the same for the third, fourth, and fifth calls. It will only execute the function on the fifth call.

Here’s an example of how the debounced function can be used:

In this example, we create a debounced version of myFunction using the debounce function. We then attach the debounced myFunction to the resize event on the window object, so that it is called whenever the window is resized.

That’s how we can execute the function only one time between a time frame. Debouncing can have a significant impact on the performance and user experience of your website or application. By limiting the rate at which a function is called, you can avoid expensive computations and DOM updates, improve the responsiveness of your website, and provide a smoother user experience.

That’s probably it for today. See you next week!

Oh another thing, If you found this helpful, you can always Buy me a Coffee or at least follow me on Twitter right?