Tjoeaon
Tjoeaon

Reputation: 1523

How to detect a scroll / wheel event only once in a certain period of time?

Let's say I have a scroll/wheel event like this:

container.addEventListener("wheel", (e) => {
  const isScrollingDown = Math.sign(e.wheelDeltaY);

  // call some function once, don't listen for wheel event anymore
  // then listen for event again when done
}

Based on deltaY, I detect whether a user is scrolling down, or up. How would I call a function only once when I detect this (which is immediatly), remove the event listener, and then listen for it again when my function is complete?

I can't remove the event listener from inside my event listener right?

Thanks in advance.

Upvotes: 1

Views: 4176

Answers (3)

Buntel
Buntel

Reputation: 622

You can use removeEventListener() function. documentation

example:

let wheelHandler = function(e) {
    toggleListener(wheelHandler, false)
    const isScrollingDown = Math.sign(e.wheelDeltaY);
    // call some function once, don't listen for wheel event anymore
    // then listen for event again when done
    toggleListener(wheelHandler, true)
};
let toggleListener = function(listener, add) {
    if (add) {
        container.addEventListener("wheel", wheelHandler)
    } else {
        container.removeEventListener("wheel", wheelHandler)
    }
}
toggleListener(wheelHandler, true);

Upvotes: 2

Vadim Hulevich
Vadim Hulevich

Reputation: 1833

wait 1 second after first wheel:

    function handleWheel(e){
          console.log(Math.random())
          document.getElementById("container").removeEventListener("wheel", handleWheel)

          setTimeout(()=>{
            document.getElementById("container").addEventListener("wheel", handleWheel);
          },1000); // return event after 1 second
    }

    
    document.getElementById("container").addEventListener("wheel", handleWheel)
<div id="container" >wheel</div>

Upvotes: 1

aseferov
aseferov

Reputation: 6393

you can define loading variable and check each time before run function

var loading = false
container.addEventListener("wheel", (e) => {
  const isScrollingDown = Math.sign(e.wheelDeltaY);

  if(!loading){
      loading = true;
     // call some function once, don't listen for wheel event anymore
     // then listen for event again when done
     // after done
     loading = false
  }
}

Upvotes: 0

Related Questions