模态需要有一个 5 秒的计时器并在之后重定向



我正在使用此代码

// 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 
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

我希望能够添加插入 5 秒计数器的功能,如下所示:

var counter = 0;
var interval = setInterval(function() {
counter++;
// Display 'counter' wherever you want to display it.
if (counter == 5) {
// Display a login box
clearInterval(interval);
}
}, 1000);

倒计时后,如果他们不点击关闭,请重定向页面:

setTimeout(function () {
//Redirect with JavaScript
window.location.href= 'http://thisinterestsme.com/php-forcing-https-over-http/';
}, 5000);

我怎样才能组合这些?

你可以做这样的事情:

具有setTimeout的"递归"函数:

var counter = 0;
var interval = function() {
setTimeout(function() {
console.log(counter++);
if (counter == 5) {
console.log("redirect");
} else {
interval();
}
}, 1000);
};
interval();

最新更新