Back to Snippets
CODE

Optimized Scroll Event Handling

Description

Combines debounce with requestAnimationFrame for high-performance scroll event handling

Code

/**
 * Optimized scroll event handler
 * @param callback Function to execute on scroll
 * @param delay Debounce delay in milliseconds
 * @returns Cleanup function
 */
function handleScroll(callback: () => void, delay = 16): () => void {
  let timeoutId: NodeJS.Timeout;
  
  const handleScroll = () => {
    cancelAnimationFrame(timeoutId);
    timeoutId = setTimeout(() => {
      requestAnimationFrame(callback);
    }, delay);
  };

  window.addEventListener('scroll', handleScroll, { passive: true });
  
  // Return cleanup function
  return () => {
    window.removeEventListener('scroll', handleScroll);
    clearTimeout(timeoutId);
  };
}

// Usage Example
const cleanupScroll = handleScroll(() => {
  console.log('Scroll position:', window.scrollY);
  // Update UI based on scroll position
}, 20);

// Cleanup when component unmounts
// cleanupScroll();

Usage

Essential for high-performance scroll-based UI updates, parallax effects, or sticky headers

Tags

PerformanceScrollEvent Handling