Skip to content

Instantly share code, notes, and snippets.

@GK-GreyGhost
Created February 7, 2022 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GK-GreyGhost/617806182f315a5a2b73ac4a4f38a78e to your computer and use it in GitHub Desktop.
Save GK-GreyGhost/617806182f315a5a2b73ac4a4f38a78e to your computer and use it in GitHub Desktop.
Countdown Library
function pad(d){
d = d.toString();
while(d.length < 2){
d = '0'+d;
}
return d;
}
function td(){
return document.createElement('td');
}
function tableRow(args){
const tr = document.createElement('tr');
for(let i = 0; i < arguments.length; i++){
const td = document.createElement('td');
td.textContent = arguments[i];
tr.appendChild(td);
}
return tr;
}
function formatTime(target){
const time = new Date(target);
const now = new Date();
const ms = time.getTime() - now.getTime();
if(ms < 0){
return 'passed';
}
const days = Math.floor(ms / (1000 * 60 * 60 * 24));
const hours = Math.floor(ms / (1000 * 60 * 60) - days * 24);
const minutes = Math.floor(ms / (1000 * 60) % 60);
const seconds = Math.floor( (ms / (1000 )) % 60 )
const div = document.createElement('div');
const table = document.createElement('table');
table.appendChild(tableRow('Days','Hours','Minutes','Seconds'));
table.appendChild(tableRow(days,hours,minutes,seconds));
div.textContent = target;
div.appendChild(table);
return div;
}
const times = document.querySelectorAll('.countdown');
for(let i = 0; i < times.length; i++){
const parts = times[i].textContent.split('-');
const title = parts[0];
const targetTime = parts[1];
function loop(){
const time = formatTime(targetTime);
if(time === 'passed'){
times[i].className += ' passed';
times[i].textContent = title;
}else{
times[i].textContent = title;
times[i].appendChild(document.createElement('hr'));
times[i].appendChild(time);
setTimeout(loop,1000);
}
};
loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment