Search code examples
javascriptdisable

How do I stop a JavaScript function once it runs


The function is when the user finishing reading the article (scroll down), will pop up an alert "You finish reading!"

But how do I disable the function when the function is triggered? Otherwise the user scroll down again, the alert will pop up again...

window.onscroll = function() {
  let trigger = true;
  
  if (trigger && window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    trigger = false;
    alert('You finish reading!');
  } else {
    return null;
  }
};

Solution

  • The short answer is to move the trigger flag outside of the event handler.

    Otherwise, you can improve this snippet by:

    1. using intersection observer for more efficient detection of the scroll to bottom
    2. otherwise, you should throttle the event handler as it is firing a lot more than necessary now and could lead to a poor UX.
    3. it would be better to window.addEventListener("scroll", () => {}) to listen for scroll events, as the onscroll property can be overridden by anyone.