<p id="timer"></p>
let countdown = function(due){
    // 現在日時を取得
     let now = new Date();
    // 現在日時と引数dueの時間の差を取得
     let rest = due.getTime() - now.getTime();
   // 差の秒の値を取得
     let sec = Math.floor(rest / 1000) % 60;
   // 差の分の値を取得
     let min = Math.floor(rest / 1000 / 60) % 60;
   // 差の時間を取得
     let hours = Math.floor(rest / 1000 / 60 / 60) % 24;
   // 差の日付を取得
     let days = Math.floor(rest / 1000 / 60 / 60 /24);
   // countに差の一覧を代入
     let count = [days, hours, min, sec];
     // countを戻す
     return count;
 }
 // 期日を設定
let goal = new Date();
goal.setDate(1);
goal.setHours(0);
goal.setMinutes(0);
goal.setSeconds(15);

 // recalcの中にファンクションを変数として代入
let recalc = function(){
  
  let now =  new Date();
  let distance = goal - now;
  if(distance < 0){
    document.getElementById("timer").innerHTML = "終了しました!";
  }else{
      // counterにcountdown(goal)の結果を代入
      let counter = countdown(goal);
    // counterの値をhtmlのIDがtimerの場所へ表示
     let time = "残りあと"+ counter[0] + "日"+ counter[1] + "時間" + counter[2] + "分" + counter[3] + "秒";
     document.getElementById("timer").textContent = time;
  
 // refreshを実行
     refresh();
  }
}
let refresh = function(){
// 指定した(1/1000 秒)時間の後にrecalcを実行
    setTimeout(recalc, 1000);
}
// recalc()を呼び出し
recalc();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.