Page Redirect after specified time with JavaScript

Page re­direction is a crucial aspect of delive­ring an uninterrupted user e­xperience in we­b development. There are scenarios where automatically redirecting users to another page after a specified time interval becomes necessary.

This article focuses on JavaScript redirects and specifically explores the implementation of a JavaScript redirect after 5 seconds.

By understanding the fundamentals of JavaScript redirects, you can gain the ability to create dynamic and timed page transitions that enhance website functionality and engagement.

Let’s dive into the world of JavaScript and learn how to achieve precise and timed page redirection for an improved user experience.

Page Redirect after specified time with JavaScript


Contents

  1. HTML Layout
  2. Implementing JavaScript Redirect after 5 Seconds
  3. Demo
  4. Conclusion

1. HTML Layout

Created a <div id='message'> container to show the message on the screen and a button for the redirect.

<input type='button' value='Submit' id='submit' onclick='pageRedirect();'> <br/>
 
<!-- Message -->
<div id="message"></div>

2. Implementing JavaScript Redirect after 5 Seconds

Upon clicking the button, invoke the pageRedirect() function to initiate the redirection process, seamlessly guiding users to a new page.

In the function defined a 5-second (5000 milliseconds) delay before executing the window.location for redirection.

NotesetTimeout() method takes duration in milliseconds, e.g. 1000  milliseconds = 1 second.

function pageRedirect(){
    var delay = 5000; // time in milliseconds

    // Display message
    document.getElementById("message").innerHTML = "Please wait, you are redirecting to the new page.";
 
    setTimeout(function(){
         window.location = "https://makitweb.com";
    },delay);
 
}

3. Demo

View Demo


4. Conclusion

To introduce a delay in executing an action, utilize the setTimeout() method. Simply place your operation code within this method, and it will automatically execute after the specified time.

In the provided demonstration, a message is displayed before initiating the redirection. However, instead of a message, you can choose to display a loader to enhance user experience during the delay period. Customize the behavior to suit your specific requirements.

If you found this tutorial helpful then don't forget to share.