Files
30-seconds-of-code/snippets/js/s/on-scroll-stop.md
2023-05-10 22:35:09 +03:00

812 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Handle scroll stop snippet javascript
browser
event
chalarangelo half-trees 2021-01-07T00:31:14+02:00

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');
});