Home > Software design >  Javascript stop loop on hover?
Javascript stop loop on hover?

Time:10-05

I wanna make an element execute a function continuously while hovering my mouse and to stop executing it when I move my mouse away from it, but right now I can only start and no idea on how to make it stop

HTML:

<a onmouseover="randomizeHover(1)" id="link1" class="link" href="#">Home</a>

JS:

function randomize(id) {
  let element = document.getElementById("link"   id);
  element.innerHTML = "Ho"   makeid(2);
}

//generates random letters

function makeid(length) {
  var result = "";
  var characters = "abcdefghijklmnopqrstuvwxyz";
  var charactersLength = characters.length;
  for (var i = 0; i < length; i  ) {
    result  = characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

//makes it repeat itself

function randomizeHover(id) {
  console.log("Hello?");
  setInterval(() => {
    randomize(id);
  }, 200);
}

CodePudding user response:

Add a mouseleave event listener that clears the interval:

function randomize(id) {
  let element = document.getElementById("link"   id);
  element.innerHTML = "Ho"   makeid(2);
}

//generates random letters

function makeid(length) {
  var result = "";
  var characters = "abcdefghijklmnopqrstuvwxyz";
  var charactersLength = characters.length;
  for (var i = 0; i < length; i  ) {
    result  = characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

//makes it repeat itself

let interval;

function randomizeHover(id) {
  console.log("Hello?");
  interval = setInterval(() => {
    randomize(id);
  }, 200);
}
function stopRandomizer(){
  clearInterval(interval)
}
<a onmouseover="randomizeHover(1)" onmouseleave="stopRandomizer()" id="link1" class="link" href="#">Home</a>

  • Related