Improved rendering with Debounce in JavaScript

Tram Ho


Have you noticed that, when you enter content in the search field, there will be a certain delay before producing the desired search results, exactly they used the debounce technique that I will talk about in the article? this. This technique will delay the process of processing the event you are manipulating such as keyup , keypress , scroll events … until the user stops manipulating a predetermined amount of time. and search autocomplete is a good example of applying this technique.

Debounce will help prevent the interface from having to handle every event called and significantly reduce the number of API calls when the user manipulates. Handling any user input can harm your performance and add unnecessary load to your server.

Without further ado, let’s dive into how to debounce it:

As the above code example, the debounce is a Higher-Order Functions , this function returns another function within it, in this code is the above code for processing timeout . The debounce function takes 2 parameters for processing.

  • fn : This parameter accepts a function you want to execute after setTimeout has executed
  • ms : The amount of time you want the debounce function to wait after taking the last action before executing fn .
  • timer : The value used to store the timeout variable each time the function is called. The timer variable is placed in the first function to avoid being created, used to store the value of the session.

And now, to understand more about how the debounce function works, let’s see the demo below.

See the example below:

Example on

Lastly, I would like to thank you all for taking a little time to read.

Reference source:

Share the news now

Source : Viblo