If you've ever noticed lag or performance issues during scroll or resize events, it’s likely because your function is being called too frequently. In such cases, throttling in JavaScript can save the day.
What is Throttling?
Throttling is a technique used to limit the execution of a function. Instead of running the function every time an event fires (like scroll or resize), it runs the function once every X milliseconds — no matter how many times the event is triggered.
This prevents performance issues and reduces the load on the browser or server.
Example Code:
Here’s a simple throttling function that limits how often your handler runs:
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function (...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function () {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
const logScroll = () => console.log("Scrolled at", new Date().toLocaleTimeString());
window.addEventListener("scroll", throttle(logScroll, 1000));
In this example, even if the user scrolls continuously, the logScroll function will only execute once every second.
Throttling vs Debouncing:
| Feature | Throttling | Debouncing |
|-----------|------------------------------|----------------------|
| Execution | Runs at intervals | Runs after the final event
| Use Case | Scroll, resize, API limiting | Search input, form validation
| Frequency | Continuous at limit rate | One final call
Benefits of Throttling:
- Improved UI responsiveness
- Reduced browser workload
- Better control over performance-heavy actions
Conclusion:
Throttling is an essential technique to master for frontend developers. It helps in optimizing performance and creating smooth, responsive user experiences.
🔗 Want to See the Full Visual Blog With Image + More?
📍 Read the full version on Blogger with image and visuals:
👉 Throttling in JavaScript on WebCodingWithAnkur
Top comments (0)