Aller au contenu principal

throttle()

throttle<Args, Context>(func, wait): (this, ...args) => void & object

Creates a throttled function that invokes at most once per wait period.

remarque

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 vs Debounce comparison

ThrottleDebounce
FiresPeriodicallyOnce, after silence
Best forScroll eventsSearch 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);