Throttling or sometimes 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. Then the number of times a button is clicked the function will be called the same number of times. Consider the example.
Without throttling Function: In this code suppose the button is clicked 500 times then the function will be clicked 500 times this is controlled by a throttling function.
Example: This example shows the above-explained approach.
HTML
< button id = "nothrottle" >Click Me</ button > < script > // Selected button with the given id const btn = document.querySelector("#nothrottle"); // Add event listener to the button // to listen the click event btn.addEventListener("click", () => { console.log("button is clicked"); }); </ script > |
Output:
With Throttling function: In this code, if a user continues to click the button every click is executed after 1500ms except the first one which is executed as soon as the user clicks on the button.
Example: This example shows the above-explained approach.
HTML
< button id = "throttle" >Click Me</ button > < script > const btn=document.querySelector("#throttle"); // Throttling Function const throttleFunction=(func, delay)=>{ // Previously called time of the function let prev = 0; return (...args) => { // Current called time of the function let now = new Date().getTime(); // Logging the difference between previously // called and current called timings console.log(now-prev, delay); // If difference is greater than delay call // the function again. if(now - prev> delay){ prev = now; // "..." is the spread operator here // returning the function with the // array of arguments return func(...args); } } } btn.addEventListener("click", throttleFunction(()=>{ console.log("button is clicked") }, 1500)); </ script > |
Output:
Advantages of throttling function:
- It prevents frequent calling of the function.
- It makes the website faster and controls the rate at which a particular function is called.