Throttling means limiting how often a function can be executed in a given time interval.
If an event (like scroll, resize, mouse move) keeps firing continuously, throttling ensures the function runs at regular intervals, not every single time.
🔹 How Throttling Works?
- Imagine you’re scrolling — the
scrollevent fires hundreds of times per second. - Without throttling → function executes too many times → performance issues.
- With throttling → function executes at most once in X milliseconds, no matter how many events occur.
🔹 Example Without Throttling ❌
window.addEventListener("scroll", () => {
console.log("Scroll event at", Date.now());
});
👉 Logs continuously on every pixel scroll → very costly!
🔹 Example With Throttling ✅
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
}
};
}
const handleScroll = throttle(() => {
console.log("Throttled Scroll at", Date.now());
}, 1000);
window.addEventListener("scroll", handleScroll);
👉 Here, no matter how fast you scroll, handleScroll will run once per second (1000ms).
🔹 Throttling in React Example
import React, { useEffect } from "react";
function App() {
useEffect(() => {
const throttle = (func, limit) => {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func(...args);
}
};
};
const handleResize = throttle(() => {
console.log("Window resized:", window.innerWidth);
}, 2000);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return <h1>Resize the window and check console!</h1>;
}
export default App;
👉 Here, window resize logs only once every 2 seconds, not continuously.
🔹 Real Use Cases of Throttling
- Handling scroll events (infinite scroll, animations).
- Handling resize events.
- Preventing too many API calls when user performs frequent actions.
- Optimizing drag and drop events.
✅ Short Interview Answer
“Throttling is a technique to limit how frequently a function executes. Even if an event fires continuously (like scroll/resize), throttling ensures the function runs only once in a fixed interval. It improves performance and prevents unnecessary computations.”