5 秒后显示 JS 警报

Ale*_*lex 2 javascript alert countdown

我试图在 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>
Run Code Online (Sandbox Code Playgroud)

问题是它不能正常工作。有一些我在代码中看不到的小错误。

小智 5

为什么要使用 setInterval 并维护一个计数变量来推断五秒过去了?

可以使用 setTimeout 简化您的代码。例如:

window.onload = setTimeout(function(){
    alert('This is an alert');
    window.location = 'http://www.example.com';
}, 5000);
Run Code Online (Sandbox Code Playgroud)