1. 程式人生 > >倒計時函數(單個和多條)

倒計時函數(單個和多條)

計時 定義 etime gettime type 單個 ret var sel

1、單個的時候

//倒計時
function countTime(endtime) {
var countDown = ‘‘
//獲取當前時間
var date = new Date();
var now = date.getTime();
//設置截止時間
var endDate = new Date(endtime);
endDate = endDate.getFullYear() > 0 ? endDate : new Date(Date.parse(endtime.replace(/-/g, "/")));
//var endDate = new Date(time);
var end = endDate.getTime();

//時間差
var leftTime = end - now;
//定義變量 d,h,m,s保存倒計時的時間
var d, h, m, s;
if (leftTime >= 0) {
d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
d = addZero(d);
h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
h = addZero(h);
m = Math.floor(leftTime / 1000 / 60 % 60);
m = addZero(m);
s = Math.floor(leftTime / 1000 % 60);
s = addZero(s);
//setTimeout(countTime,1000);
//d<1?(countDown=h+‘:‘+m+‘:‘+s):(countDown=d+‘:‘+h+‘:‘+m+‘:‘+s);
countDown = d + ‘:‘ + h + ‘:‘ + m + ‘:‘ + s;
} else {
//結束時
countDown = ‘00:00:00:00‘;


}
return countDown;
};

//補零
function addZero(str) {
if (str.toString()
.length < 2) {
str = ‘0‘ + str;
}
return str;
};


調用:
getCountDown() {
var that = this;
that.countDown = countTime(EndTime);
var singalTime = setInterval(function () {
that.countDown = countTime(EndTime)
}, 1000);
if(that.countDown==‘00:00:00:00‘){
clearInterval(singalTime)
}
},

2、多條列表同時倒計時

var Alarm = function (endtime, countFunc, endFunc) {
var date = new Date();
var startime = date.getTime();
var endDate = new Date(endtime);
endDate = endDate.getFullYear() > 0 ? endDate : new Date(Date.parse(endtime.replace(/-/g, "/")));
endtime = endDate.getTime();
this.time = Math.floor((endtime - startime) / 1000); //時間
this.countFunc = countFunc; //計時函數
this.endFunc = endFunc; //結束函數
this.flag = ‘t‘ + Date.parse(new Date());
};
Alarm.prototype.start = function () {
var self = this;
self.flag = setInterval(function () {
if (self.time < 0) {
clearInterval(self.flag);
self.endFunc();
endTimeTimedTask();
Reload();
} else {
var minute, hour, day, second;
day = Math.floor(self.time / 60 / 60 / 24) < 10 ? ‘0‘ + Math.floor(self.time / 60 / 60 / 24) : Math.floor(self.time / 60 / 60 / 24);
hour = Math.floor(self.time / 60 / 60 % 24) < 10 ? ‘0‘ + Math.floor(self.time / 60 / 60 % 24) : Math.floor(self.time / 60 / 60 % 24);
minute = Math.floor(self.time / 60 % 60) < 10 ? ‘0‘ + Math.floor(self.time / 60 % 60) : Math.floor(self.time / 60 % 60);
second = Math.floor(self.time % 60) < 10 ? ‘0‘ + Math.floor(self.time % 60) : Math.floor(self.time % 60);

//倒計時執行函數
self.countFunc(second, minute, hour, day);
self.time--;
}
}, 1000);
}

調用:
for (var i = 0; i < list.length; i++) {
list[i].showTime = countTime(list[i].endTime);
(function (ele) {
alarm = new Alarm(ele.endTime, function (second, minute, hour, day) { //計時鐘
var timeStr = day + ‘:‘ + hour + ‘:‘ + minute + ‘:‘ + second;
ele.showTime = timeStr;
}, function () { //倒計時結束
ele.showTime = ‘00:00:00:00‘
});
alarm.start();
})(list[i]);
that.resultList.push(list[i]);

}

倒計時函數(單個和多條)