Javascript 悬停时停止循环?

Javascript stop loop on hover?

我想让一个元素在鼠标悬停时连续执行一个函数,当我将鼠标移开时停止执行它,但现在我只能开始,不知道如何让它停止

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);
}

添加一个mouseleave清除间隔的事件侦听器:

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>