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 executes repeatedly until the interval is not been cleared.
In this tutorial, I show how you can use the setTimeout() method to set some delay before redirecting to another page.
Contents
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()
function from where redirecting the user to the new page.
I have defined 4 seconds (4000 milliseconds ) delay for the execution of window.location
.
Note –
setTimeout()
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 = "https://makitweb.com"; },delay); }
3. Demo
4. Conclusion
You can either use setTimeout()
or setInterval()
method to add some delay to the execution of an action.
Put your operation code and it will automatically execute in your defined time.
In the demonstration, I displayed a message before redirecting but you can use also display a loader instead of a message.
If you found this tutorial helpful then don't forget to share.