Timed JavaScript Redirect

You might know that you can use JavaScript to redirect to another page. But did you know that you can tell JavaScript to wait before it does this redirect?

You can create a timed JavaScript redirect using the following code (replacing the URL with the URL that you want to redirect to).

Timed Redirect Function

There may be times when you want a JavaScript timed redirect, but you don't want it to redirect as soon as the page loads. You might only want it to kick in after an event occurs on the page.

To do this, place your timed redirect code into a function. Then you can call it with any event handler you like.

In these examples, the page will only redirect if the user has JavaScript enabled on their browser. If you want a timed redirect to occur regardless, try using an HTML redirect. Note that if you use HTML, your timed redirects will occur when the page loads.

Redirecting to Multiple URLs

Let's improve our JavaScript function a little bit. Here, we will modify our function so that we can pass in the URL of our choice, as well as the amount of time we want it to wait before redirecting. By doing this, we won't need to "hardcode" the variables in the JavaScript above the function as we did above.

Modifying our function will enable us to call it from multiple places on the same page (for example, we could call the function from two different buttons - each with a different URL to redirect to).

In order to do this, the change is very simple. All we need to do is tell the function to accept two parameters - one for the URL, and one for the timeout period. We do this by placing the variable names in the brackets, separated by a comma. Like this: