LoginSignup
4
2

More than 5 years have passed since last update.

カウントダウン

Last updated at Posted at 2016-10-17

デモ:http://codepen.io/mo4_9/pen/wzEjJO

スクリーンショット 2016-10-17 21.37.11.png

class Countdown {

    constructor(opts={}) {
        this.$root = opts.$root || $('.countdown');
        this.$d = this.$root.find('.cd_d .num');
        this.$h = this.$root.find('.cd_h .num');
        this.$m = this.$root.find('.cd_m .num');
        this.$s = this.$root.find('.cd_s .num');

        this.endDate = Date.parse(opts.endDate) || Date.now() + 60 * 1000 * 5;

        this.init();
    }

    init() {
        this.loopId = setInterval(() => {
            const cd = this.getCount();
            this.$d.text( cd.d );
            this.$h.text( cd.h );
            this.$m.text( cd.m );
            this.$s.text( cd.s );
        },1000);
    }

    getCount() {
        const startDate = Date.now();
        const leftTime = this.endDate - startDate;
        const a_day = 24 * 60 * 60 * 1000;
        // day
        const d = this.set2fig( Math.floor(leftTime / a_day) );
        // hour
        const h = this.set2fig( Math.floor((leftTime % a_day) / (60 * 60 * 1000)) );
        // 残時間 / 秒 = 残分数
        // 残分数 % 60 = 残時間の分
        const m = this.set2fig( Math.floor((leftTime % a_day) / (60 * 1000)) % 60 );
        // 残時間 / ミリ秒 = 残秒数
        // 残秒数 % 60 = 残ミリ秒
        // 残ミリ秒 % 60 = 残時間の秒
        const s = this.set2fig( Math.floor((leftTime % a_day) / 1000) % 60 % 60 );

        // 終了
        if ( leftTime <= 0 ) {
            clearInterval( this.loopId );
            return {d:'00',h:'00',m:'00',s:'00'};
        }
        return {d,h,m,s};
    }

    set2fig(num) {
      return _.padStart(num,2,0);
    }

};

(() => {

  const countdown = new Countdown({
    endDate: '2020-08-01 00:00:00'
  });

})();

時間制御系ライブラリ
https://momentjs.com/
https://date-fns.org/

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

4
2
0

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
4
2