Skip to main content

Command Palette

Search for a command to run...

What is Debouncing in JavaScript?

Published
2 min read
What is Debouncing in JavaScript?
R

19, Hustler.


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); 
 }
}

Using a debounce

userNameInput.addEventListener(
  "keyup", 
  _debounce(checkUser, 500); 
 );

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 🍞

M

Nice article.

2
R
Rahul5y ago

Thank You

1

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.