我正在使用此代码进行倒计时,以在加载模式后重定向页面:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal and begin countdown
btn = document.getElementById('myBtn');
modal = document.getElementById('myModal');
btn.onclick = function() {
modal.style.display = "block";
(function(){
var countdown = 5;
setInterval(function() {
countdown--;
if (countdown >= 0) {
span = document.getElementById("countdown");
span.innerHTML = countdown;
}
// Display 'counter' wherever you want to display it.
if (countdown === 0) {
window.location.href= 'https://www.google.com';
clearInterval(countdown);
}
}, 1000);
})();
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
clearInterval(countdown);
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
clearInterval(countdown);
}
}
我认为,如果有人只是关闭模态,则底部的clearInterval会停止计数器,但似乎不起作用。如果有人单击模态或单击X,我该怎么做才能使计数器停止。
答案 0 :(得分:0)
var handle
在顶部,然后
handle = setInterval(function(...) {...});
然后
clearInterval(handle);