我正在尝试创建类似“退出弹出窗口”的内容,但仅限于在我的页面上停留时间少于 10 秒的用户。我想使用setInterval:
var counter = 0;
var myInterval = setInterval(function () {
// count
console.log(counter);
// Clear if more than 10 seconds
if ( 10 < counter ) {
console.log('Stop setInterval');
clearInterval(myInterval);
}
++counter;
}, 1000);
if ( 10 > counter ) {
// Simplified exit popup function
$(window).mouseleave(function() {
console.log('Popup');
clearInterval(myInterval);
});
}
代码的第一部分可以工作,但即使计数器大于 10,第二部分也会执行。为什么这不能正常工作?
最佳答案
不需要计数器。只需在页面加载时绑定(bind)
事件,然后使用setTimeout
在X秒后取消绑定(bind)
它:
$(window).bind('mouseleave', exitPopup);
setTimeout(function(){
$(window).unbind('mouseleave', exitPopup);
},10000);
function exitPopup(){
alert('Exit popup');
}
JS Fiddle Demo (3 seconds)
对于此演示,请确保在开始时将光标放在右下窗口中,并等待 3 秒钟。之后它不应该出现。如果您不等待,它将显示弹出窗口。关于javascript - 退出弹出窗口+setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034551/