Skip to content

Instantly share code, notes, and snippets.

@airton
Created January 2, 2018 19:42
Show Gist options
  • Save airton/b370c110b815c1fe2a86dd97225e1c8b to your computer and use it in GitHub Desktop.
Save airton/b370c110b815c1fe2a86dd97225e1c8b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Countdown</title>
</head>
<body>
<span id="days">00</span>
<span id="hours">00</span>
<span id="minutes">00</span>
<span id="seconds">00</span>
<script src="countdown.js"></script>
<script>
// var examplecallbackfunction = function(){
// console.log('Done');
// }
// countdown('12/12/2014 04:38:50 PM', ['days', 'hours', 'minutes', 'seconds'],
// examplecallbackfunction);
countdown('12/12/2014 04:35:00 PM', ['days', 'hours', 'minutes', 'seconds'], function(){
console.log('Finished');
});
</script>
</body>
</html>
var countdown = function(end, elements, callback){
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24,
end = new Date(end),
timer,
calculate = function(){
var now = new Date(),
remaining = end.getTime() - now.getTime(),
data;
if(isNaN(end)){
console.log('Invalid date/time');
return;
}
if(remaining <= 0){
// clear our timer
clearInterval(timer);
// callback
if(typeof callback === 'function'){
callback();
}
}else{
if(!timer){
timer = setInterval(calculate, _second);
}
data = {
'days': Math.floor(remaining / _day),
'hours': Math.floor((remaining % _day) / _hour),
'minutes': Math.floor((remaining % _hour) / _minute),
'seconds': Math.floor((remaining % _minute) / _second)
}
if(elements.length){
for(x in elements){
var x = elements[x];
data[x] = ('00' + data[x]).slice(-2);
document.getElementById(x).innerHTML = data[x];
}
}
}
};
calculate();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment