π§ What is Throttling in JavaScript?
In JavaScript, throttling is a technique to:
Limit how often a function can execute within a given time interval
π― One-Line Difference from Debounce
Debounce β run after user stops
Throttle β run at most once every X ms
β‘ Problem Throttling Solves
Some events fire continuously:
scroll
resize
mousemove
π Without control:
Scroll β function fires 100+ times/sec β
π With throttling:
Scroll β function fires every 200ms β
π¬ Core Idea
βAllow execution only once per time windowβ
π§© Step-by-Step Example
Scenario: Throttle with 1000ms (1 second)
User scrolls continuously.
Timeline
Time: 0ms 200ms 400ms 600ms 800ms 1000ms
Events: β β β β β β
Run: β
β β β β β
π Only first and after 1s β execution happens
βοΈ How It Works Internally
Key idea:
Track last execution time
Ignore calls until delay passes
π» Basic Throttle Implementation
javascript
function throttle(fn, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn.apply(this, args);
}
};
}
π Step-by-Step Internal Flow
- First call
lastCall = 0
now = 1000
β execute function
β lastCall = 1000
- Next call (within delay) now = 1200
1200 - 1000 = 200 < 1000 β
β ignore
- After delay now = 2000
2000 - 1000 = 1000 β
β execute again
π§ Visual Flow
Event β Check time β Execute or Ignore
βοΈ Alternative Implementation (Timer-Based)
function throttle(fn, delay) {
let timer = null;
return function (...args) {
if (!timer) {
fn.apply(this, args);
timer = setTimeout(() => {
timer = null;
}, delay);
}
};
}
π How This Version Works
First call β executes immediately
Sets a lock (timer)
Ignores calls until timer resets
β‘ Real-World Example
Scroll Handler
window.addEventListener(
"scroll",
throttle(() => {
console.log("Scroll handled");
}, 200)
);
π Instead of 100+ calls/sec β controlled calls
π§ Use Cases
β
Best for:
Scroll tracking
Window resize
Mouse movement
Button spam prevention
βοΈ Throttle vs Debounce (Deep Comparison)
π₯ Advanced Throttle (Leading + Trailing)
function throttle(fn, delay, options = { leading: true, trailing: true }) {
let lastCall = 0;
let timer;
return function (...args) {
const now = Date.now();
if (!lastCall && options.leading === false) {
lastCall = now;
}
const remaining = delay - (now - lastCall);
if (remaining <= 0) {
clearTimeout(timer);
lastCall = now;
fn.apply(this, args);
} else if (!timer && options.trailing !== false) {
timer = setTimeout(() => {
lastCall = Date.now();
timer = null;
fn.apply(this, args);
}, remaining);
}
};
}
π§ Leading vs Trailing
β οΈ Common Mistakes
β Using debounce instead of throttle (wrong use case)
Scroll β use throttle
Input β use debounce
β Losing this context
Use:
fn.apply(this, args)
π§ Mental Model
Throttle = βRun at fixed intervals, no matter how many events happenβ
π― Final Takeaway
- Throttling controls execution frequency
- Ensures consistent performance
- Critical for UI-heavy applications


Top comments (0)