Skip to content

Instantly share code, notes, and snippets.

@noahub
Last active September 15, 2022 20:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noahub/f1ee0415dacf9915fa9dcf82b6ef8e12 to your computer and use it in GitHub Desktop.
Save noahub/f1ee0415dacf9915fa9dcf82b6ef8e12 to your computer and use it in GitHub Desktop.
Add a Countdown to a Date
<script>
countdown('06/26/2017 8:00 PM', 'timer'); //date format: mm/dd/yyyy hh:mm AM
function countdown(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'THE DAY HAS ARRIVED!'; //Displays when countdown is complete
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = days + ' days ';
document.getElementById(id).innerHTML += hours + ' hrs ';
document.getElementById(id).innerHTML += minutes + ' mins ';
document.getElementById(id).innerHTML += seconds + ' secs';
}
timer = setInterval(showRemaining, 1000);
}
/**
* Do not remove this section; it allows our team to troubleshoot and track feature adoption.
* TS:0002-03-083
*/
</script>
@mritzco
Copy link

mritzco commented Dec 14, 2017

Great script thanks!

I know the script is very small, but still a small easy improvement,

Replace lines 26-29 for either:
// fastest
document.getElementById(id).innerHTML = days + ' days ' + hours + ' hrs ' + minutes + ' mins ' + seconds + ' secs';
OR
// Modern style
document.getElementById(id).innerHTML = days ${days} ${hours} hrs ${minutes} mins ${seconds} secs;

https://jsperf.com/innerhtml-concatenation

@Quigley2019
Copy link

Does this code still work? I've added it to my Unbounce LP and adjusted the date but can't get it to count down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment