Hello Everyone!! Here is information on JavaScript’s Debouncing and Throttling.
In modern web development, handling user input is a crucial task. Debouncing and throttling help to understand how we could manage user input to achieve better performance and effective responsive applications. So we can say that debouncing and throttling can decide how and when to trigger a set of code as per user input. This is like when we want to trigger a function, but only once per use case.
Let’s dive into these two techniques to understand with examples.
Debouncing: Debouncing makes sure that a function is called only after a specified amount of time has passed since the last invocation. Here, it delays the execution till the user stops typing in the input box.
Code example
<!DOCTYPE html>
<html lang="en">
<body>
<h1>JavaScript Debounce Example</h1>
<div class="container" style="height: 300px; width: 400px; background-color: #d0e2e2; align-content: center; text-align: center; padding: 20px;">
<button type="button" id="pressButton" style="padding:12px">Press the button</button>
<div>See console and check that the message displays after 3 seconds</div>
</div>
<script>
var button = document.getElementById("pressButton");
const debounce = (func, wait) => {
let bounceTimer;
return function() {
const context = this;
const args = arguments;
clearTimeout(bounceTimer);
bounceTimer = setTimeout(() => func.apply(context, args), wait);
}
}
button.addEventListener('click', debounce(function() {
console.log("This message will be displayed after 3 seconds, no matter how many times we click the button.");
}, 4000));
</script>
</body>
</html>
Output Screen
Here, the console displays the message only once after the click event is completed, and this function does not consider multiple click actions. So when we want the function to execute only once after the event is logged, then we go for debounce.
Example scenarios
- Search box suggestions: We will show some suggestions only when the user enters some texts and then stops entering/typing, making sure not to generate many API requests.
- Implementing delayed actions such as showing a loading symbol for some specified time and waiting for some animations to complete.
- Click event of a button/how many times we should click on a button: When we have a button, debouncing makes sure to consider the first click and ignores multiple clicks.
- Input text field’s auto-save functionality.
Throttling: Throttling controls the function calls to a specified time interval and makes sure that the function is not called more than once during the mentioned interval.
Example code Snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>JavaScript Throttling Example</h1>
<div class="container" style="height: 300px; width: 400px; background-color: #d0e2e2; align-content: center; text-align: center; padding: 20px;">
<button id="pressButton" style="padding:12px" role="button">Press this Button</button>
<div>Check console to see the time difference</div>
</div>
<script>
const button = document.querySelector("#pressButton");
// Throttling Function
const limitFunctionCall = (callback, waitTime) => {
// Previously called time of the function
let lastCalled = 0;
return (...args) => {
let currentTime = new Date().getTime();
// Logging the difference between previously called and current called timings
console.log("Time difference:", currentTime - lastCalled, "Total wait time:", waitTime);
if (currentTime - lastCalled > waitTime) {
lastCalled = currentTime;
return callback(...args); // Run the function again
}
}
}
button.addEventListener("click", limitFunctionCall(() => {
console.log("Button has been pressed! Check the time difference")
}, 1500));
</script>
</body>
</html>
Output Screen
Here, the click event logs continuously at the specified time. So, when we want the function to execute at regular intervals on a consistent basis during the event execution, then we would choose throttling.
Example scenarios
- Button click event spamming: Throttling prevents multiple button clicks by the user knowingly or unknowingly, ensures a single click event is noted for the server, and ignores other clicks. So, a single action can be taken for the click event.
- Implementing auto-complete functionality, ensuring that API requests to fetch auto-complete suggestions are not sent multiple times when a user is typing. In such a way, it reduces the load.
- In Scroll events, throttling is used to limit the number of scroll event handlers so that they are not executed too frequently, and the scroll event is smoothly handled.
- In managing resizing window event handlers, throttling could be used to prevent multiple calculations and layout updates, improving performance.
Conclusion
These two techniques help to reduce the number of API requests, unnecessary computations, and function executions, as well as avoid unnecessary network calls. Both excellently help in performance improvement and smooth execution of the application. Meanwhile, it improves the responsiveness of the application. Overusage of these causes delays in the execution, which may affect the look and feel of the application.