X

Js

Making a Redirect Page - Pt. 2

August 2, 2020

/*

The JavaScript

*/

Let's make the javascript for a redirect page. Create a main.js file in the same directory. We're going to use a timer to count down a few seconds, then send our user to another page. There's already a spot in our html for the timer.

We're going to declare a para variable which is going to grab our p.p2 element & we're going to assign a secs variable with the number 3. The first thing I want to do is make sure the page is loaded before we start our timer. For that we're going to add the load event listener to the window object. This waits until the window is loaded, then runs a user defined callback function.

/*

The Legendary setInterval()

*/

SetInterval used to be the go to for timers and animations, but with requestAnimationFrame & css transitions being so strong there's not a whole lot of use for it these days. I want to pull it out to remember how many times it made me awesome apps(If your an advanced programmer, don't think about the callback Hell or the accuracy and performance issues). SetInterval takes two arguments, a user defined callback & the timer of the intervals in milliseconds. It returns an Id value that is used with clearInterval() to stop the timer. To make simpler the funtion you define will run every number of seconds you put for the second argument.

Let's call setInterval() with a 1000 millisecond interval and set it's return value to stopInt. Inside setInterval we're going to make an if statement that will stop the timer if the secs variable equals 0, then redirect this page to another. We're going to use clearInterval(stopInt) to stop the timer. Then, we're going to use window.location equals whichever url of your choice to redirect the page.

If secs doesn't equal 0, we want secs to decrease by 1 & make the para element innerHTML say 'You will be redirected in ' + secs. Every second will have the secs count down to the page being redirected.

The result should look like this.

You could also use window.history.back() to go back to the previous page.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.