Debouncing in JavaScript
Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page which 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. Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often that it stalls the web page's performance. In other words, it limits the rate at which a function gets invoked.
let us take a real-time example of an e-shop site, we have a search box where we search for some product and it will give you suggestions related to your query,
let's assume there is an API call made when you search. In a normal input field when you call a function it will invoke at every keystroke, which means the API call is triggered for each keystroke entered, executing that many calls will impact browser performance.
Solution: debouncing will come as a saviour in such cases, the basic logic to solve this issue is when users pause between the two keystrokes, then call the API
HTML: onkeyup, we are calling the debounce method.
Javascript: https://codepen.io/ajinkyakhandar/pen/KKQOXbX
Code Explanation:
let debounce = doSomeMagic(getCount, 300) onkeyup we are calling the debounce method, which will do some magic over getCount method, here getCount method we can assume a function which calls the search API.
In doSomeMagic we pass two arguments a getCount function and the delay between two keystrokes,
The doSomeMagic will return a function, so we can execute the debounce()
To add a delay between keystrokes will set a timeout which takes "d" as a delay
context and args which handles the arguments for getCount if any
After every API execution we are clearing the timeout
Subscribe to my newsletter
Read articles from Ajinkya Khandar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by