Skip to content

Instantly share code, notes, and snippets.

@rawnly
Created May 21, 2017 19:29
Show Gist options
  • Save rawnly/e0963448ef8ac53c97991add97147320 to your computer and use it in GitHub Desktop.
Save rawnly/e0963448ef8ac53c97991add97147320 to your computer and use it in GitHub Desktop.
Countdown function in pure js (no jquery)
// @author: Rawnly
// @version: 1.0.0
// @url: https://rawnly.com
function countDown(id, date = "Jan 5 2018") {
var int = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = date - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById(id).innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById(id).innerHTML = "00d 00h 00m 00s";
}
}, 1000);
return int;
}
// EXAMPLE
// var c = countdown('myCountDown', "Jan 5, 2020");
// THAN IF YOU WANT TO CLEAR IT
// clearInterval(c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment