Debouncing in JavaScript
- Debouncing is a technique, use of Denouncing we can write better performance code that gets executed repeatedly within a period of time
- Debouncing ensures that time is taken to task, debouncing prevent unnecessary event on the web
- Debouncing code ignores unnecessary calls until the call has stopped for a particular time period.
- It is called the only the original function
Implementing Debounce:
- Time start initial value zero.
- When the user types something debouncing function call again and again but the original function when stops typing, and the timer resets a particular delay.
- That time call debouncing function.
Example:
<html lang="en"> <head> <title>Document</title> </head> <body> <input type="text" onkeyup="debouncingFunction()" /> <p id="demo"></p> <script> let count = 0; const dataFetch = () => { document.getElementById("demo").innerHTML = `Data Fetching ..${count}`; }; const Debouncing = function (fanc, delay) {let time; return function (arguments) { clearTimeout(time); time = setTimeout(() => { fanc.apply(this); }, delay); } }; const debouncingFunction = Debouncing(dataFetch, 1000); </script> </body> </html>
Debounce is a higher-order function. Which is to return another function, in debouncing function make a closure around the func and delay are two-parameter pass in Debouncing() function,
Debouncing function return another function its function have debouncing logic according to the above example user type something in the input box as well as call debouncing function again and again until the user stops the typing when the user stops the typing according to delay time call the dataFetch() function, its Overall Debouncing concept
I hope this is useful.