DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Debouncing for beginners by a beginner
newbiehritick
newbiehritick

Posted on

Debouncing for beginners by a beginner

I am a beginner and I recently learned debouncing and throttling ,their usage and differences.

Debouncing

Debouncing is a procedure in JavaScript(and possibly other programming languages) which helps us to reduce the number of function calls in response to an event.
For understanding and simplicity sake let us suppose we need to make API calls for "keyup" events on an input element.

function makeAPICall() {
   //Making API Call
}

document.querySelector("input").addEventListener("keyup",makeAPICall)
Enter fullscreen mode Exit fullscreen mode

If we use the above method and suppose I typed "Hritick" in 1 go in the input element a total of 7 API calls will be made (for each character typed) but most probably the application should only make the API call for "Hritick" or "Hrit" but we made an API call for each new character inserted which is very expensive.
So to solve this problem we can use Debouncing - by using debouncing we will make the API call only if the event (triggering the API call) hasn't taken place for a given iterval of time.

function makeAPICall() {
   //Making API Call
}

function debounce(fn, delay) {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(fn, delay);
  };
}

const optimisedFunction = debounce(makeAPICall, 500);

document.querySelector("input").addEventListener("keyup", optimisedFunction);
Enter fullscreen mode Exit fullscreen mode

In the above code we created an "optimisedFunction" for debouncing. Instead of directly making API calls on every "keyup" event we will make the API call 500 milliseconds after every "keyup" event and by using the concept of closures we will cancel every request for API call before the current "keyup" event by using clearTimeout(...).
Thus making the API call only when the user has stopped typing or have slowed down typing.
As the title said I am a beginner so if I made any mistakes or anyone has any question please comment me. And I'll make sure I correct or answer the comment.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!