为了账号安全,请及时绑定邮箱和手机立即绑定

如何停止超时?

如何停止超时?

ABOUTYOU 2023-10-14 16:52:57
我被卡住了,当我在 2 秒后打开页面时,我想显示随机项目 1 秒。然后再重复一次。但是当我悬停项目时我想停止动画。我怎样才能以正确的方式做到这一点?那一刻我有这个解决方案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)});会很高兴有任何帮助https://codepen.io/Timonck/pen/BaLKrBw
查看完整描述

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

});


查看完整回答
反对 回复 2023-10-14
  • 1 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信