使用JavaScript等待X秒后的页面重定向

vir*_*rus 63 javascript jquery

我需要在输入错误消息后5秒后重定向到特定的URL.首先,我使用了如下的Javascript.

document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000));
Run Code Online (Sandbox Code Playgroud)

但它不是等待5秒钟.比我在谷歌搜索问题而不是知道在文档加载到DOM而不是在Web浏览器上时调用"document.ready()".

比我使用jQuery的window.load()函数,但我仍然没有得到我想要的东西.

$(window).load(function() {
               window.setTimeout(window.location.href = "https://www.google.co.in",5000);
            });
Run Code Online (Sandbox Code Playgroud)

任何人都可以让我知道我需要做什么等待5秒钟.

ajt*_*rds 109

它看起来你几乎就在那里.尝试:

if(error == true){

    // Your application has indicated there's an error
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "https://www.google.co.in";

    }, 5000);

}
Run Code Online (Sandbox Code Playgroud)

  • html 替代 <meta http-equiv="refresh" content="4; URL=../device_user/email_keyboard_one_pint.html"> (3认同)

pal*_*aѕн 30

实际上window.setTimeout()你需要在5000毫秒之后传递一个你要执行的函数,如下所示:

$(document).ready(function () {
    // Handler for .ready() called.
    window.setTimeout(function () {
        location.href = "https://www.google.co.in";
    }, 5000);
});
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息: .setTimeout()


shu*_*eel 26

您可以使用此JavaScript函数.在这里,您可以向用户显示重定向消息,并重定向到给定的URL.

<script type="text/javascript">   
    function Redirect() 
    {  
        window.location="http://www.newpage.com"; 
    } 
    document.write("You will be redirected to a new page in 5 seconds"); 
    setTimeout('Redirect()', 5000);   
</script>
Run Code Online (Sandbox Code Playgroud)


Moh*_*dil 9

你需要传递一个函数 setTimeout

$(window).load(function () {
    window.setTimeout(function () {
        window.location.href = "https://www.google.co.in";
    }, 5000)
});
Run Code Online (Sandbox Code Playgroud)


小智 7

setInterval()在指定时间后使用JavaScript 方法重定向页面.以下脚本将在5秒后重定向页面.

var count = 5;
setInterval(function(){
    count--;
    document.getElementById('countDown').innerHTML = count;
    if (count == 0) {
        window.location = 'https://www.google.com'; 
    }
},1000);
Run Code Online (Sandbox Code Playgroud)

可以在此处找到示例脚本和实时演示 - 使用JavaScript延迟后重定向页面


sde*_*ont 6

$(document).ready(function() {
    window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});
Run Code Online (Sandbox Code Playgroud)