Back to Snippets
CODE
Throttle Function
Description
Limits function execution frequency to specified interval, perfect for scroll/resize events and button clicks
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));Usage
Essential for optimizing high-frequency events like scroll, resize, mousemove, or rapid button clicks