Blog>
Snippets

Custom Scroll Handling and Event Debouncing

Provide an example of custom scroll event handling using TanStack Virtual, including how to debounce scroll events to optimize performance.
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};
This function creates a debounced version of a passed function. It delays the execution of the function until after wait milliseconds have elapsed since the last time it was invoked.
const handleScroll = debounce(() => {
  console.log('Scroll event debounced.');
  // Your logic to handle the scroll event
}, 200);
This creates a debounced version of the scroll event handler. It utilizes the debounce function to limit how often the handler is called during scroll events, boosting performance.
window.addEventListener('scroll', handleScroll);
This adds an event listener to the window object that listens for scroll events and calls the debounced scroll event handler.