gpt4 book ai didi

javascript - 如果用户单击 Javascript 或 Jquery 中的 div,则停止执行函数

转载 作者:行者123 更新时间:2023-11-28 13:05:21 25 4
gpt4 key购买 nike

当用户加载页面时,我会触发一个“计时器”,该计时器将在 8 秒后显示消息。我的问题是,如果用户在这 8 秒之前单击 div #contentAfterIntro,我想阻止显示消息。

xoxo();
function xoxo(e) {
setTimeout(showMessage, 8000);
$("#contentAfterIntro").on('click', function(e) {
e.stopPropagation();
});
}

function showMessage() {
$('#msg').addClass('visible');
console.log('show msg');
}

上面的代码不起作用。在我的测试中,即使我在 8 秒之前单击,也会显示消息。

如何实现这一目标?

最佳答案

setTimeout 返回一个可用于取消超时的 ID:

xoxo();
function xoxo(e) {
var id = setTimeout(showMessage, 8000);
$("#contentAfterIntro").on('click', function(e) {
e.stopPropagation();
clearTimeout(id); // <--- clear timeout
});
}

function showMessage() {
$('#msg').addClass('visible');
console.log('show msg');
}

关于javascript - 如果用户单击 Javascript 或 Jquery 中的 div,则停止执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com