倒计时组件

倒计时组件:

function Countdown(leavetime) {
        this._init(leavetime);
    }

  Countdown.prototype = {
      _init : function (leavetime) {
          this.timer = null;
          this.leavetime = leavetime || 0;
          this.clock = {};
          this.clock.leavetimeSec = Math.floor(this.leavetime / 1000);
      },
      _format : function () {
          this.clock.sec = this.clock.leavetimeSec % 3600 % 60;
          this.clock.min = Math.floor(this.clock.leavetimeSec % 3600 / 60);
          this.clock.hours = Math.floor(this.clock.leavetimeSec / 3600);
          this.clock.secStr = String(this.clock.sec).length == 1 ? ('0' + this.clock.sec) : String(this.clock.sec);
          this.clock.minStr = String(this.clock.min).length == 1 ? ('0' + this.clock.min) : String(this.clock.min);
          this.clock.hourStr = String(this.clock.hours).length == 1 ? ('0' + this.clock.hours) : String(this.clock.hours);
      },
      run : function (doFn, endFn) {
          var that = this;
          this._format();
          doFn(this.clock);
          if (this.clock.leavetimeSec == 0) {
              clearTimeout(this.timer);
              endFn(this.clock);
              return this;
          }
          this.clock.leavetimeSec --;
          this.timer = setTimeout(function () {
              that.run(doFn, endFn);
          }, 1000)
      }
  };

 

使用:(为说明使用,运用了jquery获取dom对象)

html: <div id="box"></div>

var Countdown = new Countdown(30000000); // 实例化倒计时

// 运行倒计时
Countdown.run(function (clock) { // clock 是个对象 挂载着小时 分钟 秒钟
    $('#box').text(clock.hourStr + ':' + clock.minStr + ':' + clock.secStr);
  }, function () { // 这里写倒计时到点的callback
    alert('结束了!')
  });

 

  

posted @ 2017-03-30 17:24  盛夏、光年  阅读(249)  评论(0编辑  收藏  举报