5 秒后显示 JS 警报

Show JS Alert after 5 seconds

我试图在 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);

您的代码运行良好。检查此 JSFIDDLE

Show JS Alert after 5 seconds

在您使用 setInterval 的地方,这意味着 timer 函数将每 1 秒执行一次,并且即使在发出警报后也会继续执行。 从开发者工具检查控制台

不确定您是否需要 setInterval 或者您是否真的在寻找 setTimeout

尝试

// ---------------- Try
function init() {
    var count = 5; // set secconds
    var counter = setInterval(timer, 1000 * count);

    function timer() {
        alert("This is an alert")
        window.location = "http://www.example.com";
        //clearInterval(counter) // stop interval
    }

}

window.onload = init;

// --------------- Or

function init() {
    var count = 5; // set secconds
    var counter = setInterval(function() {
        alert("This is an alert")
        window.location = "http://www.example.com";
        //clearInterval(counter) // stop interval
    }, 1000 * count);
}

//window.onload = init;



// --------------- Or

function init() {
    var count = 5; // set secconds
    var counter = setTimeout(function() {
        alert("This is an alert")
        window.location = "http://www.example.com";
    }, 1000 * count);
}

//window.onload = init;

你可以使用简单的方法是

$(document).ready({

setInterval(showAlert(), 5000);
});

function showAlert() {
alert("This is an alert");
window.location = "http://www.example.com";      
return;
enter code here

注意:1 秒等于 1000,所以你想要这个功能运行5 秒后你需要设置 5000。

您的代码运行良好。只是由于某些原因,您的 init 函数没有在 window 加载时被调用。尝试直接调用您的函数或使用 document.body.onload 或在 HTML 文件末尾插入脚本标记,在正文中:

//I have a thing of cleaning up code
function init() {
  var count = 5;
  var counter = setInterval(timer, 1000);
  function timer(){
    count -= 1; //count = count-1 and count -= 1 are the same
    if (count === 0) { //use triple equals sign
      clearInterval(counter); //delete the interval when we are done with it
      alert("This is an alert"); //semi-colon
      window.location = "http://www.example.com";
      return;
    }
  }
}
//Instead of releying on a event, we can just call the function directly
init();
//Or you can check out the HTML for another way
<!DOCTYPE html>
<html>
  <body>
    <!--
    All you content will go here.
    And then the script will be placed right after it. It will be ran when the whole document is loaded.
    You can do something like this -->
    <script>/*function init() {...*/</script>
  </body>
</html>