Page Redirect after specified time with JavaScript

In JavaScript, setTimeout() and setInterval() methods are used to add delay before executing some action.

The setTimeout() method only executes the statement once but the setInterval() method execute repeatedly until the interval is not been cleared.

In this tutorial, I show how you can use setTimeout() method to set some delay before redirecting to another page.

Page Redirect after specified time with JavaScript


Contents

  1. HTML
  2. JavaScript
  3. Demo
  4. Conclusion

 

1. HTML

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

Completed Code

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

 

2. JavaScript

On the button click call the pageRedirect() method from where redirecting the user to the new page.

I have defined 4 seconds (4000 milliseconds ) delay for execution of window.location.

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

Completed Code

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

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

 

3. Demo

Click on the button.


 

4. Conclusion

You can either use setTimeout() or setInterval() method to add some delay for execution of an action.

Put your operation code and it will automatically execute on your defined time.

In the demonstration, I displayed a message before redirecting but you can use also display a loader instead of a message.

Related Post

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *