Detecting when user stopped scrolling

We want to listen for scroll events using addEventListener. We’ll set a delayed timeout function to run a few milliseconds after the event, but with each scroll event we’ll clear that timeout function so it doesn’t run.

When scrolling has stopped, the delayed function doesn’t get cleared and runs.

// Setup isScrolling variable
var isScrolling;

// Listen for scroll events
window.addEventListener('scroll', function ( event ) {

  // Clear our timeout throughout the scroll
  window.clearTimeout( isScrolling );

  // Set a timeout to run after scrolling ends
  isScrolling = setTimeout(function() {

    // Run the callback
    console.log( 'Scrolling has stopped.' );

  }, 66);

}, false);

References
https://gomakethings.com/detecting-when-a-visitor-has-stopped-scrolling-with-vanilla-javascript/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.