Debouncing vs. Throttling in JavaScript: When and How to Use Them
When working with JavaScript, especially in web applications, handling user interactions efficiently is crucial. Events like scrolling…
Debouncing vs. Throttling in JavaScript: When and How to Use Them
When working with JavaScript, especially in web applications, handling user interactions efficiently is crucial. Events like scrolling, resizing, keypresses, and button clicks can fire multiple times within a short period, potentially causing performance issues and unnecessary computations.
To manage these rapid events, debouncing and throttling are two essential techniques that every developer should master.
In this blog, we’ll dive deep into what debouncing and throttling are, how they work, and when to use them effectively.
Photo by Caspar Camille Rubin on Unsplash
Understanding Debouncing in JavaScript
What is Debouncing?
Debouncing ensures that a function executes only after a certain period of inactivity. If the function is triggered multiple times, the timer resets, and execution occurs only after the last event.
This is particularly useful for search boxes, resizing events, and form validation, where we want to delay execution until the user stops triggering the event.
How Debouncing Works
The logic behind debouncing is simple:
- Set a timer whenever an event occurs.
- If another event is triggered before the timer completes, reset the timer.
- If no new event occurs within the delay period, execute the function.
Basic Debounce Implementation
Let’s implement a simple debounce function in JavaScript:
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
This function takes:
func→ the actual function that should execute.delay→ the time (in milliseconds) to wait before execution.
Example: Debouncing a Search Input
Imagine an autocomplete search bar where we want to fetch results only after the user stops typing for a while.
function fetchData(query) {
console.log(`Fetching data for: ${query}`);
}
const searchInput = document.getElementById("search");
searchInput.addEventListener("input", debounce((event) => {
fetchData(event.target.value);
}, 500));
👉 In this case, fetchData will only be called 500ms after the user stops typing, preventing unnecessary API requests.
Understanding Throttling in JavaScript
What is Throttling?
Throttling ensures that a function executes at most once within a specified time interval, even if the event fires multiple times.
This is useful for scenarios like scrolling, resizing, or tracking mouse movement, where frequent execution can slow down performance.
How Throttling Works
Throttling works by:
- Allowing the function to execute immediately when called.
- Preventing execution for a defined interval after the first call.
- Once the interval ends, the function is allowed to execute again.
Basic Throttle Implementation
Here’s how to implement a simple throttle function in JavaScript:
function throttle(func, interval) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
func.apply(this, args);
}
};
}
This function ensures that func is only executed once every interval milliseconds.
Example: Throttling a Scroll Event
Let’s say we want to track scroll position, but we don’t want to execute the function too frequently:
function trackScrollPosition() {
console.log(`Scrolled to: ${window.scrollY}`);
}
window.addEventListener("scroll", throttle(trackScrollPosition, 1000));
👉 This ensures trackScrollPosition is executed only once every second, even if the user scrolls continuously.
Debouncing vs. Throttling: When to Use Which?
Both debouncing and throttling control how often a function executes, but their use cases differ:
- Use Debouncing When:
- You want to execute a function only after the user stops performing an action.
- Common use cases:
- Search input boxes (trigger API calls only after typing stops).
- Form validation (validate only after typing is complete).
- Window resize events (adjust layout after resizing stops).
2. Use Throttling When:
- You want to limit execution to fixed intervals regardless of event frequency.
- Common use cases:
- Scroll tracking (reduce event frequency for performance).
- Mouse movement tracking (detect mouse position updates).
- Button clicks (prevent multiple submissions within a short period).
Advanced Use Case: Combining Debouncing and Throttling
Sometimes, you may need both debouncing and throttling for better control.
Imagine a window resize event where:
- You want to update some UI only after the user stops resizing (debouncing).
- But you also want to log the resize event at intervals while the user is resizing (throttling).
Here’s how to combine them:
const logResize = throttle(() => console.log("Resizing..."), 500);
const finalizeResize = debounce(() => console.log("Resize completed"), 1000);
window.addEventListener("resize", (event) => {
logResize();
finalizeResize();
});
👉 This logs “Resizing…” at most every 500ms and logs “Resize completed” only after 1 second of inactivity.
Final Thoughts
Mastering debouncing and throttling is crucial for writing efficient and performant JavaScript applications.
- Debouncing ensures execution only after a delay (great for search, validation, and resize events).
- Throttling ensures execution at controlled intervals (ideal for scroll, mouse movement, and rapid clicks).
- Combining both gives fine-grained control over event handling.
By using these techniques effectively, you can enhance user experience, improve performance, and reduce unnecessary function calls in your applications.
💡 Got questions or want to share your experience? Drop a comment below! 🚀
메타데이터
- post_id
- abc4faa857fa
- slug
- debouncing-vs-throttling-in-javascript-when-and-how-to-use-them-abc4faa857fa
- url
- https://medium.com/@dinushansriskandaraja/debouncing-vs-throttling-in-javascript-when-and-how-to-use-them-abc4faa857fa
- canonical_url
- https://medium.com/@dinushansriskandaraja/debouncing-vs-throttling-in-javascript-when-and-how-to-use-them-abc4faa857fa
- author_url
- https://medium.com/@dinushansriskandaraja
- status
- ok
- fetched_at
- 2026-08-29 19:00:49