DEV Community

Cover image for What is Debouncing in JavaScript?
Rahul
Rahul

Posted on

9 2

What is Debouncing in JavaScript?

Debouncing in JavaScript means you can control the rate at which a function can execute. You can also think of Debouncing as High Order Function which is used to control the limit at which a function can execute.

Creating a debounce

function _debounce(cb, delay) {
 let time; 
 return function() {
  clearTimeout(time); 
  time = setTimeout(cb, delay); 
 }
} 
Enter fullscreen mode Exit fullscreen mode

Using a debounce

userNameInput.addEventListener(
  "keyup", 
  _debounce(checkUser, 500); 
 ); 
Enter fullscreen mode Exit fullscreen mode

On each keypress, the checkUser will trigger after 500ms.

But why Debouncing 🤔

It is used while doing a SEARCH on your webpage.

Ex. When the user starts typing, after three characters we hit the DB to fetch the search results. But if the user is typing faster, it might become a race condition in fetching the data. So to obtain it in a proper sequence we must use Debouncing.

You probably know:

  • Window resize event
  • Scroll Events
  • Autosave feature
  • Input search feature

🤔Thanks For Reading | Happy Coding 🍞

Get weekly newsletter of amazing articles I posted this week and some offers or announcement. Subscribe from Here

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay