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: https://codepen.io/ajinkyakhandar/pen/eYMONyG
Code Explanation:
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.
In doSomeMagic we pass two arguments a getCount function and the interval.
The doSomeMagic will return a function, so we can execute the throttle()
To add a delay for the getCount method will set a timeout which takes “d” as a delay
context and args which handles the arguments for getCount if any
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);
After execution of the getCount method will set a “flag=false” to stop executing the method.
next getCount will only execute after the delay so we put the “flag=true” inside setTimeout
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
Subscribe to my newsletter
Read articles from Ajinkya Khandar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by