Handle scroll stop

Angelos Chalaris · JavaScript, Browser, Event · Jan 6, 2021

Runs the callback whenever the user has stopped scrolling.

  • Use EventTarget.addEventListener() to listen for the 'scroll' event.
  • Use setTimeout() to wait 150 ms until calling the given callback.
  • Use clearTimeout() to clear the timeout if a new 'scroll' event is fired in under 150 ms.
const onScrollStop = callback => {
  let isScrolling;
  window.addEventListener(
    'scroll',
    e => {
      clearTimeout(isScrolling);
      isScrolling = setTimeout(() => {
        callback();
      }, 150);
    },
    false
  );
};
onScrollStop(() => {
  console.log('The user has stopped scrolling');
});

Recommended snippets

  • Handle user input change

    JavaScript, Browser

    Runs the callback whenever the user input type changes (mouse or touch).

  • Handle click outside

    JavaScript, Browser

    Runs the callback whenever the user clicks outside of the specified element.

  • Observe element mutations

    JavaScript, Browser

    Creates a new MutationObserver and runs the provided callback for each mutation on the specified element.