What are Debounce and Throttle?
When users interact with your website – like typing into a search bar, scrolling the page, or resizing the window – those actions can happen frequently and rapidly. If your JavaScript code responds to every single event immediately, performance can degrade quickly.
That’s why debounce and throttle are essential techniques to control how often a function is executed, helping your application remain smooth and responsive.
1. What is Debounce?
Debounce ensures that a function is only executed after a specific amount of time has passed without any further interaction.
In other words, if the user keeps triggering the event (e.g., typing), the function will be delayed until they stop for a set time (e.g., 300ms).
🎯 Real-world example:
In a live search feature, you don’t want to call the API every time the user types a letter. Debounce waits until the user finishes typing and then makes a single call.
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
const handleSearch = debounce((query) => {
console.log("Calling API with:", query);
}, 300);
input.addEventListener("input", (e) => {
handleSearch(e.target.value);
});
2. What is Throttle?
Throttle limits how often a function can be called by only allowing one call per specified time interval.
🎯 Real-world example:
When tracking scroll events, you don’t want to run your logic dozens of times per second. Throttle ensures your function runs at regular intervals – say every 200ms – no matter how often the user scrolls.
function throttle(fn, interval) {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn(...args);
}
};
}
const handleScroll = throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 200);
window.addEventListener("scroll", handleScroll);
3. When to Use Debounce vs Throttle?
Use Case | Choose | Reason |
---|---|---|
Typing in search input | debounce |
Wait until the user stops typing |
Window resize | debounce |
Avoid frequent layout recalculations |
Scroll tracking | throttle |
Limit how often logic runs |
Mouse move tracking | throttle |
Prevent performance issues |
Input validation | debounce |
Reduce unnecessary validations |
4. Quick Comparison
Debounce | Throttle | |
---|---|---|
How it works | Waits for inactivity before running function | Runs function at regular intervals |
Execution rate | Once, after delay | Many times, but limited |
Think of it like | “Wait until user stops” | “Run every X ms” |
Best for | Search, resize | Scroll, drag, mouse movement |
5. Using Lodash to Improve Debounce and Throttle
Lodash provides ready-made debounce
and throttle
functions, making it easier to use without needing to implement the algorithms from scratch.
🎯 How to Use Lodash with Debounce
Lodash provides a debounce
function that is simple to use, allowing you to just pass in the function you want to call and the delay time. For example:
import { debounce } from "lodash";
const handleSearch = debounce((query) => {
console.log("Calling API with:", query);
}, 300);
input.addEventListener("input", (e) => {
handleSearch(e.target.value);
});
🎯 How to Use Lodash with Throttle
Similar to debounce
, Lodash also provides a throttle
function to limit the frequency of function execution:
import { throttle } from "lodash";
const handleScroll = throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 200);
window.addEventListener("scroll", handleScroll);
Using Lodash helps you save time and avoid errors when re-implementing debounce and throttle functions. Moreover, Lodash also supports many other useful utilities like type checking, array and object manipulation, making your code more concise and easier to maintain.
6. Conclusion
Debounce and throttle are powerful techniques that help you control how often your functions execute, making your web apps more efficient and user-friendly.
Next time you're working with real-time inputs or high-frequency events, consider whether your code needs a bit of “restraint” — and let debounce or throttle handle it for you!
Discover more exciting blogs at: vunguyenit.site