Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!