- The Frontend Feed
- Posts
- Debouncing in JavaScript: Improve Your Web Performance
Debouncing in JavaScript: Improve Your Web Performance
When building web applications, you often need to handle events like keystrokes, window resizing or button clicks. However, these events can fire off rapidly, leading to performance issues. This is where debouncing comes into play.
Google Search Autocomplete
What is Debouncing?
Debouncing is a technique used to limit the rate at which a function is executed. Instead of executing the function immediately upon every trigger, debouncing ensures that the function is only called after a specified period of inactivity.
A debounce is utilised when you only care about the final state (such as displaying search results). The debounce function delays the processing of the event until the user has stopped typing for a predetermined amount of time.
How Does Debouncing Work?
Let’s say you have a search input field that triggers an API call with every keystroke. Without debouncing, every key press would send a new request, which can overwhelm your server and cause lag. By applying debouncing, the function waits for a pause (e.g., 300ms) in typing before making the API call.
function debounce(func, timeout){
let timer;
// waits for timeout before executing the function.
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
// Console logs will be written only after 300ms delay from user search
const handleSearch = debounce((query) => {
// API call logic here
console.log('API call with query:', query);
}, 300);
// search Input element
document.getElementById('searchInput').addEventListener('input', (event) => {
handleSearch(event.target.value);
});
When to Use Debouncing?
• Search Input Fields: To limit API calls as users type.
• Resize Events: To optimize performance when users resize the window.
• Form Validation: To avoid unnecessary checks on each keystroke.
Leading Debounce and When to Use It
In some cases, you might want to execute a function immediately when an event first occurs, rather than waiting for the user to stop interacting. This is where leading debounce comes in. Unlike a standard debounce, which delays the execution until after a period of inactivity, a leading debounce triggers the function on the leading edge of the event, ensuring the action is taken as soon as the event begins.
// useful for multiple button clicks where we need to register the first click itself.
function debounce_leading(func, timeout = 300){
let timer;
return (...args) => {
// function is called as the first event occurs
if (!timer) {
func.apply(this, args);
}
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
}, timeout);
};
}
When to Use Leading Debounce?
• Immediate Feedback: When you need to provide instant feedback, such as in real-time form validation or button click actions.
• First Action Priority: When the first action is critical, like registering the first click in a series of rapid clicks.
Further Reading:
By incorporating debouncing in your JavaScript code, you can enhance performance, reduce server load, and improve user experience. Stay tuned for our next topic, where we’ll explore throttling in JavaScript!
🚀 If you enjoyed this post, why not show your love for coding with our Javascript Developer Themed Tees from Usha Creations? Discover the perfect shirt for your next hackathon!
Reply