In general debouncing is a method or a way to execute a function when it is known that no further event will be triggered in a given interval of time.
A technical example of this concept will be a search functionality on an ecommerce website where a search functionality is there and you don’t want to trigger a search function and make a request to the server each time as the user keeps typing each letter.
In the above example, we have created a basic HTML page in which we have created an input box. We have also used onkeyup event in the input which calls a method getData(). This getData method will get data from the server or the hidden API and feeds the data.
When I typed laptop in the search box then we can clearly see in the console that the API call was made 6 times. We are trying to achieve a use case where the when the user pauses while typing then only the API call should be made.
Without calling this getData method again and again. We should create a betterFunction which should actually dosomeMagic onto our getData method. It should do someMagic and not call our getData method in each and every keystroke. Rather it should call when the user is paused while typing. If the difference in time is greater than 300 ms then only we need to call the getData method. Only doSomeMagic will call the getData method when the difference of time is greater than 300ms or 300ms.
Now let us write doSomeMagic method which will return me a function again. Let us make it an anonymous function. This function will be the betterFunction(). And this betterFunction() will be called on the keyup. Instead of calling the getData method which will be called again and again we will wait for sometime which is the delay and then we will call that function.
The delay is achieved by using the setTimeout() method.