如何在循环中执行事件,直到事件为真



我在Javascript中卡住了,当事件侦听器被调用时,循环一段代码放置.

例如,我们有一个div:

<div id="option">
</div>

和我添加了一个Javascriptmouseenter事件监听器:

const divItem = document.getElementById("option")
divItem.addEventListner("mouseenter", () => {
console.log("Mouse is entered")
})

现在控制台日志发生一次,在我悬停鼠标之后,但我希望它每隔4秒发生一次并在控制台中记录相同的消息,直到鼠标移出div。

我尝试使用setTimeout:

divItem.addEventListner("mouseenter", () => {
const timeoutEvent = () => {
console.log("Mouse is entered")
setTimeout( () => { timeoutEvent() }, 4000 )
}
timeoutEvent()
})

但是即使鼠标离开div,它也在记录,怎么解呢?

你做对了。如果你想每四秒一次,你需要:

  • 使用setInterval(或每次设置一个新的setTimeout),
  • 当你看到mouseleave
  • 时取消它

const divItem = document.getElementById("option")
// The timer handle so we can cancel it
let timer = 0; // A real timer handle is never 0, so we can use it as a flag
divItem.addEventListener("mouseenter", () => {
console.log("Mouse is entered");
timer = setInterval(() => {
if (timer) {
console.log("Mouse is still here");
}
}, 1000);
})
divItem.addEventListener("mouseleave", () => {
console.log("Mouse left");
clearInterval(timer);
timer = 0;
});
<div id="option">
this is the div
</div>

(在这个例子中我使用了1秒而不是4秒,所以更容易看到它的工作。)

或者使用setTimeout重新调度自己:

const divItem = document.getElementById("option")
// The timer handle so we can cancel it
let timer = 0; // A real timer handle is never 0, so we can use it as a flag
const timerInterval = 1000;
function tick() {
if (timer) {
console.log("Mouse is still here");
timer = setTimeout(tick, timerInterval);
}
}
divItem.addEventListener("mouseenter", () => {
console.log("Mouse is entered");
timer = setTimeout(tick, timerInterval);
})
divItem.addEventListener("mouseleave", () => {
console.log("Mouse left");
clearTimeout(timer);
timer = 0;
});
<div id="option">
this is the div
</div>

您应该使用setInterval而不是setTimeout

你可以在全局范围内定义你的'interval'函数和interval,然后使用它们来设置和启动间隔执行和clearInterval(停止执行)在mouseenter/mouseleave事件

const divItem = document.getElementById("option")
let myInterval;
const timeoutEvent = () => {
console.log("Mouse is entered")
}
divItem.addEventListener("mouseenter", () => {
myInterval = setInterval(timeoutEvent, 1000);
})
divItem.addEventListener("mouseleave", () => clearInterval(myInterval))
<div id="option">
My Option
</div>

divItem.addEventListener("mouseenter", () => {
console.log("Mouse is entered");
timer = setInterval(() => {
console.log("Mouse is still here");
}
}, 4000);
})

相关内容

  • 没有找到相关文章

最新更新