Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active April 29, 2019 10:27
Show Gist options
  • Save reecelucas/578003fcbad63726d84e898f0e51e1b2 to your computer and use it in GitHub Desktop.
Save reecelucas/578003fcbad63726d84e898f0e51e1b2 to your computer and use it in GitHub Desktop.
A simple native JS countdown timer
function getRemainingTime(endtime) {
if (typeof endtime !== 'object') {
throw new Error('getRemainingTime expects a Date object');
}
const total = Date.parse(endtime) - Date.parse(new Date());
return {
total: total,
days: Math.floor(total / (1000 * 60 * 60 * 24)),
hours: Math.floor((total / (1000 * 60 * 60)) % 24),
minutes: Math.floor((total / 1000 / 60) % 60),
seconds: Math.floor((total / 1000) % 60)
};
}
function initialiseTimer({ timer, endtime }) {
let timeInterval;
const dayElem = timer.querySelector('.js-countdown-days');
const hourElem = timer.querySelector('.js-countdown-hours');
const minuteElem = timer.querySelector('.js-countdown-minutes');
const secondElem = timer.querySelector('.js-countdown-seconds');
function updateTimer() {
const t = getRemainingTime(endtime);
if (t.total >= 0) {
dayElem.innerHTML = (`0${t.days}`).slice(-2);
hourElem.innerHTML = (`0${t.hours}`).slice(-2);
minuteElem.innerHTML = (`0${t.minutes}`).slice(-2);
secondElem.innerHTML = (`0${t.seconds}`).slice(-2);
}
if (t.total <= 0) clearInterval(timeInterval);
}
updateTimer();
timeInterval = setInterval(updateTimer, 1000);
}
function initialiseCountdownTimers({ timers }) {
if (!timers || !Array.isArray(timers)) return;
timers.forEach((timer) => {
const countdownEnd = timer.getAttribute('data-countdown-end');
if (countdownEnd) {
const endtime = new Date(Date.parse(countdownEnd));
initialiseTimer({ timer, endtime });
}
});
}
export default initialiseCountdownTimers;
<div class="js-countdown-timer" data-countdown-end="Mon, 11 Dec 2017 14:00:00 GMT">
<span class="js-countdown-days">00</span>
<span class="js-countdown-hours">00</span>
<span class="js-countdown-minutes">00</span>
<span class="js-countdown-seconds">00</span>
</div>
import initialiseCountdownTimers from './initialiseCountdownTimers';
const countdownTimers = [...document.querySelectorAll('.js-countdown-timer')]; // or Array.from(...)
initialiseCountdownTimers({
timers: countdownTimers
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment