Javascript 如何停止超时?
我卡住了 当我在2秒钟后打开页面时,我想在1秒钟内显示随机项。然后再重复一遍。但当我悬停项目时,我希望停止动画。 我怎样才能以正确的方式做这件事? 那一刻我有了这个解决方案Javascript 如何停止超时?,javascript,Javascript,我卡住了 当我在2秒钟后打开页面时,我想在1秒钟内显示随机项。然后再重复一遍。但当我悬停项目时,我希望停止动画。 我怎样才能以正确的方式做这件事? 那一刻我有了这个解决方案 let element = document.getElementsByClassName("triger"); const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max)); console.log(windo
let element = document.getElementsByClassName("triger");
const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max));
console.log(window.TIMERS)
const run = () => {
let random = getRandomInt(3);
element[random].classList.add("hover");
setTimeout(() => {
element[random].classList.remove("hover");
return setTimeout(run, 2000);
}, 1000);
};
const timeID = setTimeout(run, 2000);
console.log(timeID)
let a = document.getElementsByClassName("triger_wrap")[0];
a.addEventListener("mouseenter", () => {
console.log('a')
clearTimeout(timeID)
});
我很乐意帮忙
在底部,您正在清除
timeID
,但函数本身已经在返回setTimeout时循环(run,2000)代码>行
您需要清除函数中的实际超时。在下面的编辑中,它可以根据您的需要工作,除了在两次清除超时之后需要另一行代码,以便在我们停止超时时从当前包含它的元素中删除.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
});