Page Redirect after specified time with JavaScript

For adding delay for execution of some action setTimeout() and setInterval() methods is begin used in JavaScript.

The setTimout() method execute the statement only once but setInterval() method execute repeatedly until the interval is not being cleared.

In this tutorial, I am using the setTimeout() method to stop the page from redirect as soon as the button gets clicked.

Page redirect after specified time with Javascript


Contents

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

 

1. HTML

Created a <div> 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 calling 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 action statements within it and it will automatically execute on your defined time.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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