Page Redirect after X seconds wait using JavaScript

I need to redirect to specific url after 5 seconds after putting an error message. First i have used Javascript as below.

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

But it is not waiting for 5 seconds. Than I searched the issue in google than come to know that "document.ready()" is invoked when document is loaded at DOM, not at web browser.

Than i have used window.load() function of jQuery but still i am not getting what i want.

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

Can anyone please let me know how exactly i need to do to wait for 5 seconds.


Solution 1:

It looks you are almost there. Try:

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);

}

Solution 2:

You actually need to pass a function inside the window.setTimeout() which you want to execute after 5000 milliseconds, like this:

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

For More info: .setTimeout()

Solution 3:

You can use this JavaScript function. Here you can display Redirection message to the user and redirected to the given 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>

Solution 4:

You need to pass a function to setTimeout

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

Solution 5:

Use JavaScript setInterval() method to redirect page after some specified time. The following script will redirect page after 5 seconds.

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

Example script and live demo can be found from here - Redirect page after delay using JavaScript