我试图在 5 秒后显示 JS 警报。现在我有这段代码:
<script>
function init() {
var count=5;
var counter=setInterval(timer,1000);
function timer(){
count=count-1;
if(count==0){
alert("This is an alert")
window.location = "http://www.example.com";
return;
}
}
}
window.onload = init;
</script>
问题是它不能正常工作。代码中存在一些我看不到的小错误。
最佳答案
为什么要使用 setInterval 并维护一个计数变量来推断五秒过去的时间?
您的代码可以使用 setTimeout 进行简化。例如:
window.onload = setTimeout(function(){
alert('This is an alert');
window.location = 'http://www.example.com';
}, 5000);
关于javascript - 5 秒后显示 JS 警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545527/