简体   繁体   中英

Delay between event listener

I've got an event listener detecting when I scroll, and when I scroll a transform happens in CSS to a div , but I want a delay so you can't perform the event right after it just happened.

document.addEventListener('wheel', event => {

  if (event.deltaY > 0) {
    wheel.style.transform = "transform";
  } else if (event.deltaY < 0) {
    wheel.style.transform = `transform * -1`;
  } else {
    return;
  }

  //I tried setTimeout but it didn't do anything for me, maybe I'm using it wrong?

  setTimeout((event) => {
    wheel.style.transform
    console.log("hi")
  }, 1000)

});

You need to use setTimeout() for the real action that you just want to do

In your current code,it just let the wheel event after 100 ms to bind it, once it binded and the event trigger,it will execute immediately

// this will just make the event bind after 100ms to work
setTimeout((event) => {
    wheel.style.transform
    console.log("hi")
  }, 100)

We can change it as below:

 document.addEventListener('wheel', event => { console.log("click event:" + new Date()) setTimeout(()=> { console.log("click event timeout:" + new Date()) if (event.deltaY > 0) { //wheel.style.transform = "transform"; } else if (event.deltaY < 0) { //wheel.style.transform = `transform * -1`; } else { return; } },3000) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM