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.
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>