Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda