Skip to content

Instantly share code, notes, and snippets.

@xuhen
Created March 26, 2020 13:39
Show Gist options
  • Select an option

  • Save xuhen/27ea881ea0e7441481def15352eaf278 to your computer and use it in GitHub Desktop.

Select an option

Save xuhen/27ea881ea0e7441481def15352eaf278 to your computer and use it in GitHub Desktop.
// html
<span id="clock"></span>
// js
(function () {
const endTime = new Date().getTime() + 10 * 24 * 60 * 60 * 1000;
const clock = document.getElementById('clock');
function getRemainingTime(deadline) {
const currentTime = new Date().getTime();
return deadline - currentTime;
}
function pad(value) {
return ('0' + Math.floor(value)).slice(-2);
}
function showTime() {
const remainingTime = getRemainingTime(endTime);
const seconds = pad((remainingTime / 1000) % 60);
const minutes = pad((remainingTime / (60 * 1000)) % 60);
const hours = pad((remainingTime / (60 * 60 * 1000)) % 24);
const days = pad(remainingTime / (24 * 60 * 60 * 1000));
clock.innerHTML = `${days}:${hours}:${minutes}:${seconds}`;
if (remainingTime >= 1000) {
console.log('showTime', remainingTime);
requestAnimationFrame(showTime);
}
}
requestAnimationFrame(showTime);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment