throttle()
throttle<
Args,Context>(func,wait): (this, ...args) =>void&object
Creates a throttled function that invokes at most once per wait period.
Executes on leading edge (immediately) and trailing edge (after wait period).
Type Parametersโ
Args: Args extends unknown[]โ
The argument types of the function.
Context: Context = unknownโ
The type of this context.
Parametersโ
func: (this, ...args) => voidโ
The function to throttle.
wait: numberโ
The number of milliseconds to throttle invocations.
Returns: (this, ...args) => void & objectโ
The throttled function with a cancel() method.
Throwsโ
RangeError If wait is negative or not finite.
Sinceโ
2.0.0
Noteโ
Call .cancel() to clear any pending execution.
Performanceโ
Uses timestamp comparison to avoid unnecessary setTimeout calls. Stores latest args/context for trailing edge execution.
Also known asโ
throttle (Lodash, es-toolkit, Remeda, Radashi, Modern Dash) ยท โ (Ramda, Effect, Antfu)
Exampleโ
// Scroll handler
const handleScroll = throttle(() => {
console.log('Scrolling...');
}, 200);
window.addEventListener('scroll', handleScroll);
// With arguments
const logMouse = throttle((x: number, y: number) => {
console.log('Mouse:', x, y);
}, 100);
document.addEventListener('mousemove', (e) => {
logMouse(e.clientX, e.clientY);
});
// Cancel pending
logMouse.cancel();
How it works?โ
Throttle enforces a maximum execution rate โ the function fires at most once per interval. Calls during the cooldown are ignored, ensuring consistent rhythm regardless of input frequency.
Throttle vs Debounceโ
Throttle enforces rhythm โ fires at fixed intervals regardless of call frequency. Debounce waits for silence โ resets on every call.
| Throttle | Debounce | |
|---|---|---|
| Fires | Periodically | Once, after silence |
| Best for | Scroll events | Search input |
Use Casesโ
Limit function execution frequency ๐โ
Control the rate of function execution to prevent performance issues. Essential for performance optimization and preventing excessive resource usage.
const logScroll = throttle(() => {
console.log("Scrolled!");
}, 100);
window.on("scroll", logScroll);
Optimize scroll and resize eventsโ
Limit the frequency of scroll and resize event handlers. Critical for responsive design and scroll-based UI. Limit animation updates to maintain smooth performance. Essential for smooth animations and visual effects.
const updateCanvas = throttle((mouseX: number, mouseY: number) => {
ctx.clearRect(0, 0, width, height);
drawParticles(mouseX, mouseY);
}, 33); // Cap at ~30fps
canvas.on("mousemove", (e) => updateCanvas(e.offsetX, e.offsetY));
Rate-limit ticket purchases during high-demand salesโ
Throttle ticket purchase requests to ensure fair access during flash sales. Essential for concert ticketing, sports events, and limited availability sales.
// Throttle purchase attempts to 1 per second per user
const attemptPurchase = throttle(async (ticketId, userId) => {
const result = await ticketingAPI.purchase({ ticketId, userId });
if (result.success) {
showConfirmation(result.ticket);
} else {
showWaitlistOption();
}
}, 1000);
buyButton.on("click", () => {
attemptPurchase(selectedTicketId, currentUserId);
});
// Throttle seat selection updates to reduce server load
const updateSeatSelection = throttle((seats) => {
api.reserveSeats(seats);
updateSeatMap(seats);
}, 500);
seatPicker.on("selection_change", updateSeatSelection);