鼠标悬停图像卡在循环中

mouseover image stuck in loop

我一直在编写此 JavaScript 代码,以便在鼠标悬停时在一帧中显示多个图像。

但我卡在了 setInterval 循环中,尽管我退出了框架,但图像仍在不断变化。

肯定卡在了函数change().

我在移动光标时找不到退出此程序的方法。

你能帮我一下吗?


let start = 0;

const imageChange = document.querySelector(".image");

imageChange.addEventListener("mouseover", set_time);
imageChange.addEventListener("mouseout", end);

function set_time() {
  setInterval(change, 1500);
}

function change() {
  if (start < 3) {
    console.log(start);
    imageChange.src = "/img/image" + start + ".jpg";
    start++;
  } else {
    start = 0;
  }
}

function end() {
  start = 0;
  imageChange.src = "/img/image" + start + ".jpg";
}

您需要使用clearInterval停止函数的连续执行。

let intvl;
function set_time() {
  intvl = setInterval(change, 1500);
}
function change() {
  if (start < 3) {
    console.log(start);
    imageChange.src = "/img/image" + start + ".jpg";
    start++;
  } else {
    start = 0;
  }
}

function end() {
  start = 0;
  clearInterval(intvl);
  imageChange.src = "/img/image" + start + ".jpg";
}