In JavaScript, throttling is a powerful technique used to control the rate at which a function executes. If your web application frequently listens for scroll, resize, or input events, throttling helps prevent excessive function calls, thereby improving performance and user experience.
But how does it work? And how do you implement it in real-world applications? Let’s dive in!
Throttling is a technique where a function is executed at most once within a specified time interval, even if it is triggered multiple times.
Imagine a scroll event firing dozens of times per second. Without throttling, your function would run on every event, potentially slowing down your page. With throttling, you can ensure the function runs only once every X milliseconds, reducing performance overhead.
✔ Prevents Performance Issues: Limits the number of function calls, reducing strain on the browser.
✔ Enhances User Experience: Prevents lag when handling events like scrolling or resizing.
✔ Optimizes API Calls: Ensures API requests are not sent too frequently, avoiding unnecessary load.
Let’s create a throttle function that limits the frequency of function execution.
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
🔹 How it works:
The function executes only if the last execution time was more than delay
milliseconds ago.
It ignores repeated calls within the delay period.
function handleResize() {
console.log("Window resized at", new Date().toLocaleTimeString());
}
window.addEventListener("resize", throttle(handleResize, 2000));
💡 Now, even if the user resizes the window rapidly, the function will only execute once every 2 seconds.
If you don’t want to write a custom function, you can use Lodash, a popular utility library.
npm install lodash
2️⃣ Use Lodash’s _.throttle()
Method
import _ from "lodash";
function handleScroll() {
console.log("Scrolled at", new Date().toLocaleTimeString());
}
window.addEventListener("scroll", _.throttle(handleScroll, 1000));
💡 This ensures handleScroll
runs once per second, no matter how fast the user scrolls.
✅ Infinite Scroll: Prevent excessive API calls when fetching new content.
✅ Form Submission: Limit how often users can submit a form.
✅ Mouse Movement Tracking: Reduce logging frequency in analytics tools.
✅ Rate Limiting API Calls: Prevent hitting API request limits by controlling the request frequency.
Throttling is an essential JavaScript performance optimization technique that ensures a function executes at controlled intervals rather than on every event trigger.
🔹 Use throttling when dealing with scroll, resize, or API request rate limiting.
🔹 Use Lodash’s _.throttle()
for a cleaner and more efficient implementation.
🔹 Choose throttling over debouncing when you need continuous execution at intervals rather than waiting for user inactivity.
🚀 Now that you understand throttling, try implementing it in your projects to improve performance!