In JavaScript, we can redirect the page after 5 seconds with the help of the setTimeout method and the window.location object.

setTimeout(function(){
  window.location.href = "https://daztech.com/";
}, 5000);

You can see in the code above that the setTimeout() method will run the function after 5000 milliseconds. We can change that parameter to be however long we want to wait to execute the function call.

Also notice that we use the href property of the location object and set that to the webpage we want to redirect the user to.

In this case, we are just redirecting the user back to the homepage.

Let’s take a look at an example below.

Using JavaScript to Redirect the Page After 5 Seconds with a Click

In this example, we will let the user click a button that will redirect the current page to the homepage after 5 seconds. The HTML will just have a button the user can click.

Here is the simple HTML setup:

Click the button below to redirect the page to the homepage.

Make sure to hit the back button once you reach the homepage to come back to this page.

Redirect

In the JavaScript portion of this example, we will start by adding an onclick event to the redirect button that will run our function.

In the function, we will first let the user know that the page will redirect in 5 seconds using the textContent property.

Then we will use the setTimeout method to run some code after 5 seconds. In this code, we will redirect the current page to the homepage: “https://daztech.com/”.

We will do this by changing the href property of the location object to the webpage we want to redirect the user to above.

Here is the JavaScript code:

//The variable below will just make it so the user can only run this once
var isSetTimmeoutRunning = false;
  
function startRedirect(){

  if( isSetTimmeoutRunning == false ){
    //We set this variable to true when we first run the setTimeout method.
    //It will get set back to false when the setTimeout method has completed
    isSetTimmeoutRunning = true;
      
    //Let the user know we will redirect them
    document.getElementById("redirect-text").textContent = "The page will redirect in 5 seconds...";

    setTimeout(function(){
      isSetTimmeoutRunning = false;
      //Redirect to homepage
      window.location.href = "https://daztech.com/";
    }, 5000);
  }
}

The final code and output for this example of how to redirect the current page after 5 seconds is below:

Code Output:

Click the button below to redirect the page to the homepage.

Make sure to hit the back button once you reach the homepage to come back to this page.

Redirect

Full Code:

Click the button below to redirect the page to the homepage.

Make sure to hit the back button once you reach the homepage to come back to this page.

Redirect

Hopefully this article has been useful for you to understand how to use JavaScript to redirect after 5 seconds.

Categorized in:

JavaScript,

Last Update: March 13, 2024