count down demo

by kakadodo

HTML

<div id="showTime"></div>

JavaScript

var showTimeDiv = document.getElementById('showTime');
const anotherDay = new Date().getTime() + 1000*60*60*24;

function showLeftTime(today, anotherDay){
  var todayTime = today.getTime();
  var anotherDayTime = anotherDay.getTime();
  var leftDayTime = (anotherDayTime - todayTime);
  
  var leftDay = Math.floor(leftDayTime/1000/60/60/24);
  var leftHours = Math.floor(((leftDayTime/1000/60/60/24) - leftDay)*24);
  var leftMinutes = Math.floor((((leftDayTime/1000/60/60/24) - leftDay)*24 - leftHours)*60);
  var leftSeconds = Math.floor(((((leftDayTime/1000/60/60/24) - leftDay)*24 - leftHours)*60 - leftMinutes)*60);
  
  showTimeDiv.textContent = '還剩下 '+leftDay+' 天 '+leftHours+' 時 '+leftMinutes+' 分 '+leftSeconds+' 秒.';
  setTimeout(showLeftTime.bind(null, new Date(), new Date(anotherDay)), 1000); //function中再次呼叫 setTimeout 可重複執行 function
}

setTimeout(showLeftTime.bind(null, new Date(), new Date(anotherDay)), 1000); //首次呼叫 setTimeout