A countdown timer on a webpage is normally used to point the tip or starting of an occasion. It may be used to let clients know when a worth supply expires, or function on a “coming quickly” touchdown web page to point when the positioning will likely be printed. It may also be used to let a person know if an motion must be carried out quickly; for instance, some web sites will log customers out of a web page if there was no exercise inside a sure time frame.
So, again to what we’re making—right here’s a take a look at the ultimate product. Press Rerun on the demo to begin the countdown perform:
Let’s get began!
1. Creating the Markup
We’ll be utilizing two sections for this demo: a timer part and a content material part. The timer part will include the weather for displaying the time left within the countdown and the content material part would be the factor proven after the countdown is up.
<part id="timer"> <p>This content material will likely be displayed in</p> <div class="timer-container"> <span id="days">0 days</span> <span id="hours">0 hours</span> <span id="minutes">0 minutes</span> and <span id="seconds">0 seconds</span> </div> </part> <part id="content material"> <h1>Hi there, World</h1> </part>
Contemplating Accessibility
Since we’re constructing a piece that has continuously altering data, we should always contemplate how this data will likely be offered to assistive applied sciences. On this demo, we’ll use the timer
function to characterize the weather which have commonly up to date textual content.
<part id="timer"> <p>This content material will likely be displayed in</p> <div class="timer-container"> <span id="days" function="timer">0 days</span> <span id="hours" function="timer">0 hours</span> <span id="minutes" function="timer">0 minutes</span> and <span id="seconds" function="timer">0 seconds</span> </div> </part> <part id="content material"> <h1>Hi there, World</h1> </part>
2. Styling the Sections
The timer container has probably the most precedence when the web page is first loaded so we’ll make it a set container that’s the total width and top of the web page so no different content material is seen until the countdown is up. We’ll additionally use an opacity styling on our content material to cover it.
#timer { place: fastened; high: 0; backside: 0; show: flex; flex-direction: column; min-height: 100vh; justify-content: heart; align-items: heart; width: 100%; z-index: 2; } #content material { opacity: 0; }
3. Constructing the Countdown Timer
That is the logic we’ll use to deal with the countdown timer:
- Outline a countdown worth based mostly on a particular date or time
- Get the present date and subtract the worth from our countdown
- Perform the subtraction perform at an interval of 1s
- If the countdown date is lower than or equal to the present date, finish the countdown
Let’s begin with defining our countdown worth. There are two doable strategies we will use:
1. Defining the Countdown Worth as a Particular Date and Time
We will initialise a countdown worth as a particular date utilizing the Date()
constructor. This technique is beneficial for displaying particular affords or reductions because the countdown finish time will all the time be fixed. For instance, you should use a countdown timer to show a reduction supply till the New Yr.
let countdownDate = new Date('01 January 2023 00:00')
2. Defining the Countdown Worth as an Added Unit of Time to the Present Date
We will additionally initialise a countdown timer by including time to the present date. This technique is beneficial for dealing with user-based timer interactions. We use the Date get and set strategies for this. For instance, you may set a timer to show content material 30 seconds after a person has landed on a webpage.
let countdownDate = new Date().setSeconds(new Date().getSeconds() + 30);
We will additionally modify this perform for minutes or hours:
let countdownDate = new Date().setMinutes(new Date().getMinutes() + 5);
let countdownDate = new Date().setHours(new Date().getHours() + 1)
As soon as we’ve setup our countdown worth, we will outline our constants:
const daysElem = doc.getElementById("days"), hoursElem = doc.getElementById("hours"), minutesElem = doc.getElementById("minutes"), secondsElem = doc.getElementById("seconds"), timer = doc.getElementById("timer"), content material = doc.getElementById("content material");
Then we will work on our countdown perform.
4. Creating the startCountdown() Operate
We’ll create a brand new perform known as startCountdown()
the place we get the present date and subtract it from the countdown date. We’ll use the Date.getTime()
technique to transform each values into milliseconds then we divide the distinction by 1,000 to transform to seconds.
const startCountdown = () => { const now = new Date().getTime(); const countdown = new Date(countdownDate).getTime(); const distinction = (countdown - now) / 1000; }
We’ll must convert the distinction worth to days, hours, minutes and seconds to find out our timer worth.
We will convert seconds to days by dividing the distinction in seconds by the worth of someday (60seconds * 60minutes * 24hours) and rounding as much as the closest worth.
let days = Math.ground(distinction / (60 * 60 * 24));
Since our countdown is an additive worth, we’ll must think about the previous values when calculating. When changing to hours, we’ll first must know what number of days are within the distinction after which convert the rest to hours.
For instance, if we now have 90,000 seconds, this will likely be transformed to 25 hours. Nevertheless, we will’t show a countdown as 1 day and 25 hours as that will likely be an incorrect time. As an alternative we’ll first calculate what number of days are within the seconds as 90000 / (60 * 60 * 24) = 1 day with a the rest of 3600 seconds. Then we will convert this the rest to hours by dividing by (60seconds * 60minutes) which supplies 1 hour.
let hours = Math.ground((distinction % (60 * 60 * 24)) / (60 * 60));
Making use of the identical cumulative division for minutes and seconds:
let minutes = Math.ground((distinction % (60 * 60)) / 60); let seconds = Math.ground(distinction % 60);
Then we’ll go our calculated values into the HTML parts. Taking grammar into consideration, we will outline a perform to format the unit of time textual content as singular or plural based mostly on the worth of time.
const formatTime = (time, string) => { return time == 1 ? `${time} ${string}` : `${time} ${string}s`; };
Our startCountdown()
perform now seems like this:
const startCountdown = () => { const now = new Date().getTime(); const countdown = new Date(countdownDate).getTime(); const distinction = (countdown - now) / 1000; let days = Math.ground(distinction / (60 * 60 * 24)); let hours = Math.ground((distinction % (60 * 60 * 24)) / (60 * 60)); let minutes = Math.ground((distinction % (60 * 60)) / 60); let seconds = Math.ground(distinction % 60); daysElem.innerHTML = formatTime(days, "day"); hoursElem.innerHTML = formatTime(hours, "hour"); minutesElem.innerHTML = formatTime(minutes, "minute"); secondsElem.innerHTML = formatTime(seconds, "second"); };
5. Working our Operate at Intervals
Now we now have our countdown perform, we’ll create a perform that runs the countdown perform at an interval of 1s.
First, we’ll create our timerInterval worth.
let timerInterval
Then we outline the timerInterval as a setInterval perform when the web page masses
window.addEventListener("load", () => { startCountdown(); timerInterval = setInterval(startCountdown, 1000); });
On this technique, we’ve known as the startCountdown()
perform instantly because the web page masses to replace the countdown values after which we name the countdown perform each 1s after the web page masses.
We’ll must additionally outline a perform to deal with when the countdown timer ends. We’ll know the timer has ended when the distinction in our startCountdown
perform is lower than 1 second.
const startCountdown = () => { const now = new Date().getTime(); const countdown = new Date(countdownDate).getTime(); const distinction = (countdown - now) / 1000; if (distinction < 1) { endCountdown(); } ... };
That is what we now have thus far!
6. When the Countdown Timer Ends
What we at present have retains counting down indefinitely, which clearly isn’t very helpful, so let’s treatment that.
In our endCountdown()
perform, we’ll cease the interval perform, delete the timer and show the content material part.
const endCountdown = () => { clearInterval(timerInterval); timer.take away(); content material.classList.add("seen"); };
We’ll goal the seen class in CSS to deal with displaying the content material. On this demo, we now have a textual content scale and background color change animation when the content material is displayed that’s additionally dealt with with CSS. After all, that is purely for demonstrative functions—you may model issues nonetheless you need.
#content material h1 { font-size: 10vmax; remodel: scale(1.25); } #content material.seen { opacity: 1; animation: colorChange 1s ease-in-out 0.5s forwards; } #content material.seen h1 { animation: scaleOut 1s ease-in-out 0.5s forwards; } @keyframes colorChange { from { colour: #fcdf00; background-color: #0d67ad; } to { colour: white; background-color: black; } } @keyframes scaleOut { from { remodel: scale(1.25); } to { remodel: scale(1); } }
Conclusion
And, with that, we’ve efficiently created a countdown timer to show content material on a webpage!