Javascript倒數計時元件new TimeSpan(hours, minutes, minutes)

rentj發表於2014-08-12
function TimeSpan(h, m, s) {

    this.h = Number(h);
    this.m = Number(m);
    this.s = Number(s);

}

TimeSpan.prototype = {

    timer: null,

    stop: function() {

    },

    callback: Function(),

    start: function(callback) {
        var self = this;

        if (callback) {

            this.callback = callback;
        }

        if (isNaN(this.s)) {
            return;
        }

        self.timer = setInterval(function() {

            self.s--;

            if (self.s >= 0) {
                self.callback();
                return;

            }

            //s < 0, m > 0
            if (self.m > 0) {
                self.s = 59;
                self.m--;
                self.callback();
                return;
            }

            //s < 0 ,m = 0, h<1
            if (isNaN(self.h) || self.h < 1) {
                //self.callback();
                clearInterval(self.timer);
                return;
            }


            self.m = 59;
            self.s = 59;
            self.h--
            self.callback();
        }, 1000);

    }
};

 

呼叫:

    var ts = new TimeSpan(hours, minutes, minutes);

    ts.start(function(){
        var s = this.s < 10 ? "0" + this.s : this.s;
        var m = this.m < 10 ? "0" + this.m : this.m; 
        $(".clock .time").html(m + "分" + s + "秒");
    });

 

相關文章