In the fast-paced world of web development, user experience is paramount. One of the key aspects of ensuring a smooth and responsive interface is managing how and when events are processed. This is where debouncing and throttling come into play. These techniques are crucial for optimizing performance and enhancing the user experience by controlling the rate at which functions are executed. Whether you're dealing with input fields that trigger search queries, scrolling events, or resizing actions, understanding and implementing debouncing and throttling can make a significant difference in the responsiveness and efficiency of your web applications. In this article, we'll explore the concepts of debouncing and throttling, their differences, and practical implementations in JavaScript to help you master user experience design.
I'll explain them simple. Here's an example of making an API call with an input field using jQuery without using Lodash. This example will simulate making a call to a dummy API every time the user types something in the input field:
<label for="inputField">Type something:</label>
<input type="text" id="inputField">
<h2>API Response:</h2>
<p id="apiResponse"></p>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#inputField').on('input', function() {
const value = $(this).val();
// Make the API call when the input value changes
$.ajax({
url: `https://jsonplaceholder.typicode.com/posts?q=${value}`,
method: 'GET',
success: function(response) {
$('#apiResponse').text(JSON.stringify(response));
},
error: function() {
$('#apiResponse').text('Error fetching data.');
}
});
});
});
</script>
If you check inspect element you will see that an API call goes to a server every time we type a letter.
It's true that we need the result for "example post". But we don't need to send API call and get results for e, ex, exa or exam. For that we can use Debouncing and Throttling
Debouncing
debouncing ensures that a function is executed only after a certain period of inactivity, reducing the number of function calls and improving performance. Let me explain it further.
const debouncedUpdate = _.debounce(function (value) {
$('#debouncedOutput').text(value);
console.log('Debounced Input:', value);
}, 1000); // 1 second debounce
They wait 1000 milisecond or 1 second before send the API call. (Or change text in $('#debouncedOutput') according to this case).
Even though you sent three API calls for this, 'exa' now it waits 1 second (1000 milliseconds) after pressing first letter before sending an API call. If you press second letter before that API call will not go.
If you type into a search box, the function debouncedUpdate will wait for 1 second after the user stops typing before executing. So, if the user types "exa" and then types more characters within that second, the debounce delay resets and the function wonโt execute until the user stops typing for a full second. This prevents unnecessary function calls or updates while the user is still typing.
Throttling
Check this example.
const throttledUpdate = _.throttle(function (value) {
$('#throttledOutput').text(value);
console.log('Throttled Input:', value);
}, 1000); // 1 second throttle
Throttling works like this. After you start typing after every 1000 milliseconds the function runs until stop typing. And make note it will run initial call too.
Hereโs how it works:
- Initial Call: When the event first occurs (e.g., typing), the function executes immediately.
- Subsequent Calls: The function will not execute again until the specified interval (e.g., 1000 milliseconds) has passed, even if the event continues to occur during that time.
- Interval Execution: After the interval has passed, if there are additional events, the function will execute again and then wait for the next interval.
So, throttling limits how frequently the function is executed during continuous events, ensuring it only runs at a controlled rate.
This is a complete example if you want to check the behavior more
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lodash Throttle and Debounce Example</title>
</head>
<body>
<h1>Lodash Throttle and Debounce Example</h1>
<label for="inputField">Type something:</label>
<input type="text" id="inputField">
<h2>Throttled Output:</h2>
<p id="throttledOutput"></p>
<h2>Debounced Output:</h2>
<p id="debouncedOutput"></p>
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Lodash CDN -->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>
$(document).ready(function () {
// Throttle example: Limits the number of times the function can execute within a time frame
const throttledUpdate = _.throttle(function (value) {
$('#throttledOutput').text(value);
console.log('Throttled Input:', value);
}, 1000); // 1 second throttle
// Debounce example: Delays the execution of the function until a certain amount of time has passed without triggering
const debouncedUpdate = _.debounce(function (value) {
$('#debouncedOutput').text(value);
console.log('Debounced Input:', value);
}, 1000); // 1 second debounce
// Event listener for input field
$('#inputField').on('input', function () {
const value = $(this).val();
throttledUpdate(value);
debouncedUpdate(value);
});
});
</script>
</body>
</html>
Top comments (0)