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,

amazon.png

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. image.png

Javascript: codepen.io/ajinkyakhandar/pen/KKQOXbX

code.png

Code Explanation:

  1. 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.

  2. In doSomeMagic we pass two arguments a getCount function and the delay between two keystrokes,

  3. The doSomeMagic will return a function, so we can execute the debounce()

  4. To add a delay between keystrokes will set a timeout which takes "d" as a delay

  5. context and args which handles the arguments for getCount if any

  6. After every API execution we are clearing the timeout

Did you find this article valuable?

Support Ajinkya's blog by becoming a sponsor. Any amount is appreciated!