Throttling in Javascript

Throttling or sometimes is also called throttle function is a practice used in websites. Throttling is used to call a function after every millisecond or a particular interval of time only the first click is executed immediately.

Let’s see, what will happen if the throttle function is not present on the web page. when your search any query for each keystroke the function will be called the same number of times. Consider the example.

Without throttling Function: In this code suppose if the user typed 500 characters then the function will be called 500 times, this is controlled by a throttling function.

HTML: onkeyup, we are calling the throttle method.

Javascript: codepen.io/ajinkyakhandar/pen/eYMONyG

image.png

Code Explanation:

  1. let throttle = doSomeMagic(getCount, 300) onkeyup we are calling the throttle method, which will do some magic over getCount method, here getCount method we can assume a function which has some logic to be executed.

  2. In doSomeMagic we pass two arguments a getCount function and the interval.

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

  4. To add a delay for the getCount method will set a timeout which takes “d” as a delay

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

  6. To execute the first call immediately will set a flag=true as default, and will check if a flag is true then execute the getCount method i.e fn.apply(context, args);

  7. After execution of the getCount method will set a “flag=false” to stop executing the method.

  8. next getCount will only execute after the delay so we put the “flag=true” inside setTimeout

  9. getCount will call immediately at first, then it will wait for the delay and then execute getCount again, using this will call the method after every millisecond

Did you find this article valuable?

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