Code Bytes
Count down to a date with plain JavaScript
Build an independent countdown with an explicit UTC deadline, a finished state, start/pause controls and cleanup instead of shared timer state.
Something to look forward to.
Choose a future date and watch the days, hours, minutes and seconds count down.
Runs automatically in your local time zone. Change the date to try your own. Pause freezes the display, not time itself.
A countdown subtracts the current time from a target date. Enable JavaScript to try one.
Count towards a real deadline
Use a countdown for an event or release time, while showing the actual date alongside it. The demo is a browser-only calculation: it does not reserve anything, change a booking or enforce a deadline.
The important detail is to subtract the current clock time on every update. Decrementing a counter once a second drifts when a background tab is slowed down.
Markup
<p>Starts <time datetime="2028-01-05T15:00:00Z">5 January 2028, 15:00 UTC</time>.</p>
<p id="countdown" role="timer" aria-live="off">Countdown is not running.</p>
<div id="countdown-controls" hidden>
<button type="button" id="start-countdown">Start</button>
<button type="button" id="pause-countdown">Pause</button>
</div>
JavaScript
Put this in a deferred script. Each call owns its own timer.
function createCountdown(output, deadline) {
if (!Number.isFinite(deadline)) throw new TypeError('A valid deadline is required');
let timer = null;
let running = false;
let destroyed = false;
function draw() {
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
output.textContent = seconds === 0 ? 'The countdown has finished.'
: `${days}d ${hours}h ${minutes}m ${seconds % 60}s`;
return seconds;
}
function tick() {
timer = null;
if (!running || document.hidden) return;
if (draw() > 0) timer = setTimeout(tick, 1000);
else running = false;
}
function start() {
if (destroyed) return;
clearTimeout(timer);
running = true;
tick();
}
function pause() {
running = false;
clearTimeout(timer);
timer = null;
}
function visibility() {
clearTimeout(timer);
timer = null;
if (running && !document.hidden) tick();
}
document.addEventListener('visibilitychange', visibility);
draw();
return { start, pause, destroy() {
pause();
destroyed = true;
document.removeEventListener('visibilitychange', visibility);
} };
}
const countdown = createCountdown(
document.querySelector('#countdown'),
Date.parse('2028-01-05T15:00:00Z'),
);
document.querySelector('#countdown-controls').hidden = false;
document.querySelector('#start-countdown').addEventListener('click', countdown.start);
document.querySelector('#pause-countdown').addEventListener('click', countdown.pause);
Dates, accessibility and cleanup
Z means UTC. For an event with a known offset, use a complete timestamp such as 2028-07-05T15:00:00+01:00; do not rely on an ambiguous date string or a visitor's local timezone. Validate user-entered calendar dates separately before converting them.
Days here are elapsed 24-hour blocks, not local calendar days across daylight-saving changes. Pause freezes the display, not the deadline; Start catches up. The timer is not a live announcement every second, and the readable deadline remains without JavaScript.
Call countdown.destroy() when removing this view in a client-routed application, and remove its button listeners along with the view. For an enforceable sales deadline, the server must make the decision: a visitor can change their clock or the script.
References: Date.parse, timer delays, and page visibility.
Original version15 August 2013
Kept here for reference and earlier links. The updated guide above is the recommended starting point; older code may depend on retired services or different software versions.
Basic Example - Counting down to Jan 5th, 2028 15:00:00
This code byte provides a very simple way of producing a dynamic countdown timer to a particular date and time using pure JavaScript. Alternatively, if you're looking for a count up javascript count-up timer, then head here: Javascript count up from date and time
Step 1: The basic HTML
<div id="countdown1" class="countdown">
<span class="timeel days">00</span>
<span class="timeel timeRefDays">days</span>
<span class="timeel hours">00</span>
<span class="timeel timeRefHours">hours</span>
<span class="timeel minutes">00</span>
<span class="timeel timeRefMinutes">minutes</span>
<span class="timeel seconds">00</span>
<span class="timeel timeRefSeconds">seconds</span>
</div>
Step 2: The Core Javascript
This is the main JavaScript that gets things going. You can either put this in your JS file that is to be included on every page that requires the countdown (Eg. main.js), or just put it in
<script></script>
tags on specific pages. Just change the parameters where the countDownToTime function is first called, by adding your desired date, and element to target as the countdown timer.
/*
* Basic Count Down to Date and Time
* Author: @guwii / guwii.com
* https://guwii.com/bytes/easy-countdown-to-date-with-javascript-jquery/
*/
window.onload = function() {
// Month Day, Year Hour:Minute:Second, id-of-element-container
countDownToTime("Jan 5, 2028 15:00:00", 'countdown1'); // ****** Change this line!
}
function countDownToTime(countTo, id) {
countTo = new Date(countTo).getTime();
var now = new Date(),
countTo = new Date(countTo),
timeDifference = (countTo - now);
var secondsInADay = 60 * 60 * 1000 * 24,
secondsInAHour = 60 * 60 * 1000;
days = Math.floor(timeDifference / (secondsInADay) * 1);
hours = Math.floor((timeDifference % (secondsInADay)) / (secondsInAHour) * 1);
mins = Math.floor(((timeDifference % (secondsInADay)) % (secondsInAHour)) / (60 * 1000) * 1);
secs = Math.floor((((timeDifference % (secondsInADay)) % (secondsInAHour)) % (60 * 1000)) / 1000 * 1);
var idEl = document.getElementById(id);
idEl.getElementsByClassName('days')[0].innerHTML = days;
idEl.getElementsByClassName('hours')[0].innerHTML = hours;
idEl.getElementsByClassName('minutes')[0].innerHTML = mins;
idEl.getElementsByClassName('seconds')[0].innerHTML = secs;
clearTimeout(countDownToTime.interval);
countDownToTime.interval = setTimeout(function(){ countDownToTime(countTo, id); },1000);
}
Step 3: Style it up
The very basic styling for the top example, I've left it simple to ensure it's
easy for everyone to edit themselves - you can do better I'm sure!
<style>
.countdown {
text-align: center;
margin-bottom: 20px;
}
.countdown .timeel {
display: inline-block;
padding: 10px;
background: #151515;
margin: 0;
color: white;
min-width: 2.6rem;
margin-left: 13px;
border-radius: 10px 0 0 10px;
}
.countdown span[class*="timeRef"] {
border-radius: 0 10px 10px 0;
margin-left: 0;
background: #e8c152;
color: black;
}
</style>Keep exploring