View profile

Debounce in JavaScript

Debounce in JavaScript
By Akash Rajpurohit • Issue #2 • View online
Create a simple reusable debounce function

The Code
Creating a utility function
Creating a utility function
How to use it?
wrap any of your function with the debounce utility we just created
wrap any of your function with the debounce utility we just created
The output
Demo of the ouput
Demo of the ouput
How it works
There are few things that are happening here
Firstly let’s talk about the function signature of debounce. It accepts a function as first argument and a duration (in milliseconds) as second argument.
It returns a debounced function as output.
So what is this debounced function??
A debounced function is a function that gets called after N amount (duration mentioned as the second argument) of time passes since its last call.
Let’s break this down in simpler terms. A debounced function will run the function you have passed as first argument only after the duration have passed and while running that function it will take in the latest instance of the function that was passed.
So this is helpful in many scenarios, for example you have a website like Amazon where you want users to filter products as they use the search box.
One thing is to fire an API call to your backend server every time user types something in the search box, but that is not the best way because firstly you would be making lots and lots of request to your backend API and most of these calls are useless.
When I say most of these calls would be useless, it is because let’s say the user wants to search for “Men Shoes” and he/she starts typing character by character, your input state would look something like this
M -> Me -> Men -> Men -> Men S -> Men Sh -> Men Sho -> Men Shoe -> Men Shoes
Here we made around 9 API calls and initial few ones are total waste because your search API is receiving a request for search text as “M” which does not make sense.
So instead you could debounce this input for let say 1000 milliseconds or a second, this way you could easily skip the initial few texts because in around 1000 milliseconds the user might have already typed the entire word “Men shoes” so your search API is called once with the whole text.
Even if the text is huge, it still makes sense to have a chunk of data instead of making an API call for every character input.
The code uses the concepts of JavaScript Closures and SetTimeout, if you don’t know much about closures you can read about it here
You can check out the code sample posted on my site under “Snippets” section.
Debounce in JavaScript
Did you enjoy this issue?
Akash Rajpurohit

A periodic update about my life, recent blog posts, how-tos, discoveries, things I am learning and amazing content for the community!

In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue