1 回答

TA贡献1828条经验 获得超3个赞
在底部,您正在清除timeID,但函数本身已经在线循环return setTimeout(run, 2000);。
您需要清除函数内的实际超时。在下面的编辑中,它按照您想要的方式工作,除了需要在两行代码之后添加另一行代码,clearTimeouts以便.hover在我们停止超时时从当前拥有该类的元素中删除该类。
let element = document.getElementsByClassName("triger");
let timeout;
const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max));
const run = () => {
let random = getRandomInt(3);
element[random].classList.add("hover");
timeout = setTimeout(() => {
element[random].classList.remove("hover");
return setTimeout(run, 2000);
}, 1000);
};
const timeID = setTimeout(run, 2000);
let a = document.getElementsByClassName("triger_wrap")[0];
a.addEventListener("mouseenter", () => {
clearTimeout(timeID)
clearTimeout(timeout);
// find element with .hover class and remove it
});
添加回答
举报