throttle
Limita la ejecución de una función a máximo una vez por intervalo.
#async
#performance
#events
#utility
export const throttle = <T extends (...args: unknown[]) => void>( fn: T, delay = 300,) => { let last = 0; let timeout: ReturnType<typeof setTimeout> | null = null;
return (...args: Parameters<T>) => { const now = Date.now(); const remaining = delay - (now - last); if (remaining <= 0) { last = now; fn(...args); } else if (!timeout) { timeout = setTimeout(() => { last = Date.now(); timeout = null; fn(...args); }, remaining); } };};
// Usageconst throttledScroll = throttle(() => { console.log('Scrolled!');}, 100);
window.addEventListener('scroll', throttledScroll);