Is there a way to fire a function only if an event is sustained for a while

Viewed 25

I'm trying to call a function only if the user hovered over the target for a certain amount of seconds. So it doesn't fire instantly and also doesn't just fire after a time frame but only fires if the user hovered for the entire duration of the timeframe. If this could be done in JavaScript it would be fantastic. Thanks in advance

1 Answers

Just set a timeout when the mouse hovers the div, and clear it when the mouse leaves the div. In this way the callback will be fired only and only if the mouse remained within the div for n seconds

const el = document.querySelector('.hover-me');

let timeoutHandler = null;
el.addEventListener('mouseenter', () => {
  timeoutHandler = setTimeout(() => alert('Hovered for 2 seconds'), 2000);
});

el.addEventListener('mouseleave', () => {
  if (timeoutHandler) clearTimeout(timeoutHandler);
  timeoutHandler = null;
});
div.hover-me {
  width: 200px;
  height: 200px;
  background-color: lightblue;
}
<div class="hover-me">Hover me</div>

Related