✅ Logical Operators in JavaScript – Complete Guide with Real Examples

Have you ever wondered how to control how often a function runs when triggered frequently — like on scroll, resize, or button click? That's where Throttling in JavaScript comes in.
Throttling is a technique used to limit the number of times a function gets called over time. Instead of calling the function every time an event fires, it ensures the function executes only once every specified interval.
resize
, scroll tracking, infinite scroll, button spam protection, etc.
Let’s say an event is triggered 50 times per second. With throttling, you can restrict the callback to run only once every 300ms or any interval you decide.
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("Scroll event at", new Date().toLocaleTimeString());
window.addEventListener('scroll', throttle(logScroll, 1000));
Both are rate-limiting techniques:
Throttling is essential when dealing with high-frequency event handlers. It helps you build efficient and responsive applications by avoiding performance bottlenecks.
Comments
Post a Comment