Blog>
Snippets

Implementing Debounced Scroll Events for Performance

Illustrate the implementation of debounced scroll events to save scroll position, minimizing performance impact during fast or frequent scrolling in SPAs.
let lastKnownScrollPosition = 0;
let isScrolling;

window.addEventListener('scroll', function() {
  lastKnownScrollPosition = window.scrollY;

  clearTimeout(isScrolling);

  isScrolling = setTimeout(function() {
    // Run the saveScrollPosition function after scrolling has stopped
    saveScrollPosition(lastKnownScrollPosition);
  }, 66); // Approximately 15 fps
}, false);
This code snippet sets up an event listener for the window's scroll event. It uses a timeout to debounce the scroll events, ensuring the saveScrollPosition function (which you would need to implement to actually save the scroll position, perhaps in local storage or a global state) is only called after the user has finished scrolling (stopping for 66 milliseconds). This significantly reduces the number of times the function is called, improving performance.
function saveScrollPosition(scrollPos) {
  // Implement saving logic here
  // For example, localStorage.setItem('scrollPosition', scrollPos);
  console.log('Scroll position saved:', scrollPos);
}
This function is a placeholder for the logic that saves the last known scroll position. You might save this position to local storage, a cookie, or some application state management solution. This example just logs the position to the console to illustrate the functionality.