Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda