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

269
Vistas
How do I remove one EventListener after another eventListener is triggered?

I am writing a code where I have to change the image inside a div(I have an array of image URLs) when I hover on it. But after I move out from that div's scope I want the image to be the default. Here is my code

div.addEventListener("mouseenter", changeImage);
      function changeImage(){
            let i=0;
            setInterval(function(){
               img.src = imageArr[i];
               if(i>=imageArr.length-1){
                  i=0;
               }else{
                  i++;
               }
            }, 2000);
      }

Here I am able to change the images after hovering over it. But even after moving out from the div's scope, the images are still changing.

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

0

I don't think your issue is really in need of removing the listener. In fact, I think you need to add another listener for mouseout that stops your interval timer:

const div = document.querySelector("div");
div.addEventListener("mouseenter", changeImage);
div.addEventListener("mouseout", stopChanges);

let timer = null; // Will hold a reference to the timer

function changeImage(){
  let i=0;
  // Store a reference to the running timer so it can be
  // referenced and stopped later.
  timer = setInterval(function(){
    // Contents changed for testing purposes
    console.log("Timer is running");
  }, 750);
}
      
function stopChanges(){
  clearInterval(timer); // Stop the timer
  console.log("Timer stopped");
}
<div>Mouse in and out of 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