Skip to content

Instantly share code, notes, and snippets.

@harm-smits
Created August 3, 2021 09:20
Show Gist options
  • Save harm-smits/41aa07fce5ee83914f9d0f5b130dd6f8 to your computer and use it in GitHub Desktop.
Save harm-smits/41aa07fce5ee83914f9d0f5b130dd6f8 to your computer and use it in GitHub Desktop.
Very simple countdown for a plaintext countdown from a given timestamp.
let selectors = {
'days' : '.js-countdown-days',
'hours' : '.js-countdown-hours',
'minutes': '.js-countdown-minutes',
'seconds': '.js-countdown-seconds'
};
/**
* Get the time remaining till a date.
*/
function calculateTimeTillDeadline(deadline) {
let diff = Date.parse(deadline) - Date.parse(String(new Date()));
return {
'diff' : diff,
'days' : Math.floor( diff / (1000 * 60 * 60 * 24)),
'hours' : Math.floor((diff / (1000 * 60 * 60)) % 24),
'minutes': Math.floor((diff / 1000 / 60) % 60),
'seconds': Math.floor((diff / 1000) % 60 ),
}
}
/**
* Countdown
* @param element
* @param options
* @return {{start: function (), stop: function (), destroy: function ()}}
*/
export function countdown(element, {timestamp})
{
if (!timestamp)
throw new TypeError(`Countdown requires a timestamp to countdown to`)
let deadline = new Date(timestamp * 1000),
interval = null;
/**
* Pad zeros to the end of a number
* @param number
* @param count
* @returns {string}
*/
function padZeros(number, count = 2)
{
let s = String(number)
while (s.length < count)
s = '0'.concat(s)
return s
}
/**
* Handle a tick
*/
function tick() {
let remaining = calculateTimeTillDeadline(deadline),
elem = null;
for (let entry in remaining) {
if (!remaining.hasOwnProperty(entry))
continue
if (selectors[entry]
&& (elem = element.querySelector(selectors[entry]))
&& elem.textContent !== padZeros(remaining[entry])
) {
elem.textContent = padZeros(remaining[entry])
}
}
if (remaining.diff <= 0)
clearInterval(interval)
}
return {
start: () => {
tick()
interval = setInterval(tick, 100)
},
stop: () => {
clearInterval(interval)
interval = null
},
destroy: () => {
clearInterval(interval)
interval = null
deadline = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment