Reputation: 1523
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
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
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
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