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 throttle function is not Present in 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 if the button is clicked 500 times then the function will be clicked 500 times this is controlled by a throttling function.
- Program:
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
meta
name
=
"viewport"
content="
width
=
device
-width,
initial-scale
=
1
.0" />
<
title
>
JavaScript | Without Throttling
</
title
>
</
head
>
<
body
>
<
button
id
=
"nothrottle"
>Click Me</
button
>
<
script
>
// Selected button with th egiven 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
>
</
body
>
</
html
>
chevron_rightfilter_none - Outout:
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.
- Program:
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
title
>
JavaScript | With Throttling
</
title
>
</
head
>
<
body
>
<
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
>
</
body
>
</
html
>
chevron_rightfilter_none - Output:
Advantages of throttling function:
- It prevent frequent calling of the function.
- It makes the website faster and controls the rate at which a particular function is called.