In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce.
Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page that requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single-threaded language.
A Debounce function is a higher-order function that returns another function, to create closure around the function parameters (func, timeout) and the timer variable.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Debouncing in Javascript</title> </head> <body> <h5>Debouncing in Javascript</h5> <input type="text" id="txtInput" /> <script src="script.js"></script> </body> </html>
const txtInput = document.getElementById("txtInput"); txtInput.addEventListener("keyup", function () { optimizeFunction(); }); let counter = 0; const getDataFromApi = () => { console.log("Getting Data....", counter++); }; const debounceMethod = function (fn, delay) { let timer; return function () { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; }; const optimizeFunction = debounceMethod(getDataFromApi, 300);
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions