LoginSignup
69
70

More than 5 years have passed since last update.

JavaScript (jQuery) でカウントダウンタイマーを書く

Last updated at Posted at 2013-12-16
countdown_timer.html
<script type="text/javascript">
  $(function() {
    countDown();
  });
  function countDown() {
  var startDateTime = new Date();
  var endDateTime = new Date("January 01,2014 00:00:00");
  var left = endDateTime - startDateTime;
  var a_day = 24 * 60 * 60 * 1000;

// 期限から現在までの『残時間の日の部分』
  var d = Math.floor(left / a_day) 

// 期限から現在までの『残時間の時間の部分』
  var h = Math.floor((left % a_day) / (60 * 60 * 1000)) 

// 残時間を秒で割って残分数を出す。
// 残分数を60で割ることで、残時間の「時」の余りとして、『残時間の分の部分』を出す
  var m = Math.floor((left % a_day) / (60 * 1000)) % 60 

// 残時間をミリ秒で割って、残秒数を出す。
// 残秒数を60で割った余りとして、「秒」の余りとしての残「ミリ秒」を出す。
// 更にそれを60で割った余りとして、「分」で割った余りとしての『残時間の秒の部分』を出す
  var s = Math.floor((left % a_day) / 1000) % 60 % 60 

  $("#TimeLeft").text(d + '' + h + '時間' + m + '' + s + '');
    setTimeout('countDown()', 1000);
  }
</script>

<div class="Timer">
  <p>カウントダウン終了まで</p>
  <div id="TimeLeft"></div>
</div>

また パシャログブログ を見たところ、カウントダウンの目標時刻はサーバー側から取得するよりクライアント側で設定した方がいいとのこと。

▼参考
getTime();について
Date();について

こういうものもあるようで、便利かも
jQuery CountDown

69
70
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
69
70