JavaScript倒计时类

时间:2023-03-09 19:22:49
JavaScript倒计时类
(function (){
var jtimer = function() {
// init
if(arguments.length >= 1) {
this.setEndTime(arguments[0]);
}
if(arguments.length >= 2) {
this.setGenerateCallBack(arguments[1]);
}
};
jtimer.prototype.setEndTime = function () {
if(arguments.length == 1) {
this.endTime = arguments[0]; // Date
}
}
jtimer.prototype.getMillisecond = function () {
return this.endTime.getTime() - new Date().getTime();
};
jtimer.prototype.setGenerateCallBack = function (callback) {
if(typeof callback == "undefined") return;
this.generateCallBack = callback;
}
jtimer.prototype.generate = function () {
if(typeof this.generateCallBack == "undefined") return;
var ms = this.getMillisecond();
this.generateCallBack(
Math.floor(ms/(1000 * 60 * 60 * 24)),
Math.floor(ms/(1000*60*60)) % 24,
Math.floor(ms/(1000*60)) % 60,
Math.floor(ms/1000) % 60
);
};
jtimer.prototype.start = function () {
var delay = 1000;
if(arguments.length == 1) {
delay = arguments[0];
}
_this = this; // for closure
this.interval = window.setInterval(
function() {
_this.generate();
}, delay);
}
jtimer.prototype.stop = function () {
if(typeof this.interval == "undefined") return;
window.clearInterval(this.interval);
this.interval = undefined;
} window.jtimer = jtimer;
})(); var jt = new jtimer(new Date("6/27/2016"), function (day, hour, min, sec) {
console.log(day + "," + hour + "," + min + "," + sec);
});
jt.start(1000);