WP-Mix

A fresh mix of code snippets and tutorials

Set Timeout and Redirect with JavaScript

Hello again! This WP-Mix tutorial shows how to set a timeout and redirect to any URL using vanilla JavaScript. It’s one line of code easy peasy.

Say you have a web page. When a visitor arrives, you want to wait three seconds and then redirect the user to some other location on the Web. There are numerous ways of doing it, here is how using vanilla JavaScript:

<script>setTimeout(function(){ window.location = 'https://example.com/'; }, 3000);</script>

There are two things that you’ll want to customize with this code:

  • The URL https://example.com/ — change to whatever you want
  • The timeout 3000 — change to any length of time (in milliseconds)

That’s all there is to it.

Here is a demo that you can add to a blank HTML file:

<!DOCTYPE html> 
<html lang="en-US">
	<head>
		<script>setTimeout(function(){ window.location = 'https://example.com/'; }, 3000);</script>
	</head>
	<body>
		<p>
			Set Timeout and Redirect with JavaScript: 
			https://wp-mix.com/set-timeout-redirect-javascript/
		</p>
	</body>
</html>

Open that in a browser and two things will happen. Yes you guessed it, first there will be a 3 second delay and then a redirect to example.com. Of course, you can change these values to whatever is useful. Again the timeout value is specified in milliseconds (ms), so 3000ms = 3 seconds.

★ Pro Tip:

Banhammer Pro