Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run the mouseover event after 3 seconds

I need to execute a function when the mouse pauses on an element for 3 seconds.
I tried to do this with the mouseover event, but the problem is that my function is triggered immediately when the mouse enters the element

 element.addEventListener("mouseover", () => {
  setTimeout(() => {
      myFunction()
   },3000)
  })

Is there a way to trigger the mouseover event after the user pauses on the element for 3 seconds?

Is there a better way?, please help me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Rather than mouseover, I’d probably use mouseenter since mouseover fires repeatedly as the mouse moves across the element. Then you can use mouseleave to cancel the timer if the mouse leaves the element before the three seconds are up.

Something like this:

const target = document.querySelector(".target");
let timer = 0;
target.addEventListener("mouseenter", () => {
    timer = setTimeout(() => {
        timer = 0;
        console.log("Timer fired");
    }, 3000);
    console.log("Timer started");
});
target.addEventListener("mouseleave", () => {
    if (timer) {
        clearTimeout(timer);
        timer = 0;
        console.log("Timer cancelled");
    }
});
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>
<div class="target">Target </div>
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>

That example only handles a single element (because timer is a single variable), but if you need to handle multiple, you could maintain a WeakMap using the element as the key and the timer handle as the value. (A WeakMap so that if the elements are removed from the DOM at some point, the map entries for them don’t stick around unnecessarily.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading