Improve performance with Debounce

I recently came across the concept of debouncing when working on a search functionality in a MERN app I was building. I quickly realized the shortcomings of sending a request to the server with every keystroke in the search box, sending requests to the server on every keystroke can potentially cause UI problems and it is also a burden on the people using your code. Making all those requests and downloading them if they are on mobile data or slow connection it will burn through their bandwidth fast and potentially slow down the app if their connection is not able to keep up.

That's where debouncing shines; instead of calling the function every single keystroke, it will only call the function after a set delay.

Example: using a basic button to illustrate how Debounce works

const btn = document.getElementById('btn')

const debounce = (cb,delay=1000)=>{
	let debounceTimer
  return ()=>{
  	clearTimeout(debounceTimer)
    debounceTimer = setTimeout(()=>{
  			cb()  
    },delay)
  }
}

btn.addEventListener('click',debounce(()=>console.log('you clicked me!!'),1000))

Let's break down what is happening in the code example above: Click event is attached to the button. The debounce function takes 2 arguments, a callback function and the expected delay time before the function is executed. If the delay is not provided in our case, it defaults to 1000 (one second). The Idea is that the function passed to the Debounce function will only execute after the set delay time if the button is clicked only once.

If the button is clicked more than once but still within the set delay time, then the timer gets reset back to the specified delay time and waits to see if there is any change, if not then the function will run.

The clearTimeout function is being used to achieve this.

Debouncing will drastically improve speed for the users of your application and potentially save you money as it reduces the quantity of requests putting demands on your server.

The general idea for Debouncing is: source of the below explanation https://www.geeksforgeeks.org/

  1. Start with 0 timeout
  2. If the debounced function is called again, reset the timer to the specified delay
  3. In case of timeout, call the debounced function Thus every call to a debounce function, resets the timer and delays the call.
DebounceJavaScript
Avatar for Fatima Aminu

Written by Fatima Aminu

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.