Throttle Function
Limits function execution frequency to specified interval, perfect for scroll/resize events and button clicks
Implementation
Copy the complete example or adapt its typed interface to your project. Comments are kept inside the snippet so the intent travels with the code.
/**
* Throttle function implementation
* @param fn Function to throttle
* @param delay Throttle interval in milliseconds
* @returns Throttled function
*/
function throttle<T extends (...args: any[]) => void>(fn: T, delay: number): T {
let lastCall = 0;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn.apply(this, args);
}
} as T;
}
// Usage Example
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event processed');
}, 200));When to use it
Essential for optimizing high-frequency events like scroll, resize, mousemove, or rapid button clicks
Review the input assumptions and browser or runtime support before adopting a utility unchanged. Small helpers are easiest to maintain when their contract stays narrow.
Reasoning and trade-offs
How it works
Throttle records when the wrapped function last ran and allows another execution only after the interval has elapsed. Calls arriving inside the window are ignored, keeping expensive work from running at full event frequency.
What to watch for
This leading-only form drops the final call, which can leave UI state stale after scrolling or resizing stops. Context, arguments, cancellation, clock changes, and async overlap should be considered before using it as shared infrastructure.
Production use
Use leading throttling for progress indicators or telemetry where periodic samples matter more than the final value. Choose a version with trailing execution when the last user action must always be reflected.
Before you ship
- Confirm the input contract with tests that cover empty, invalid, boundary, and representative real-world values before sharing the helper across a codebase.
- Keep the function focused on one responsibility and name any project-specific policy explicitly instead of hiding it inside a generic-looking utility.
- Measure behavior in the browsers or runtime versions your product supports, especially when timing, storage, DOM state, locale, or network access is involved.
- Document the return type, mutation behavior, failure mode, and performance characteristics beside the call site so future maintainers can evaluate changes safely.
- Compare the example with current official platform documentation when it relies on a browser API, language feature, or runtime behavior that may change over time.
- If the helper crosses a trust boundary, validate again on the server and avoid treating browser-side checks, TypeScript annotations, or formatted output as a security guarantee.
- Add a small regression test whenever a real edge case is discovered; concrete examples preserve the reason behind a guard more reliably than a general comment.