最新項目上用到一個JS計時器,缺點是沒有做setTimeOut的管理,只能啓動一個計時器。
JS計時器,工具類,用法:
<span style="font-size:14px;">var timer = TimeUtils.getTimer().start("#Id“);//啓動
timer.stop();//停止
timer.getStartTime();//獲取開始時間
timer.getStopTime();//獲取停止</span>
源碼:
<span style="font-size:14px;">var TimeUtils = {
/**
* 獲取一個計時器
*/
getTimer: function() {
return new timerCount();
}
};
window.TimeUtil = TimeUtils;
/**
* 啓動計時器
*/
function timerCount() {
this.sTime = null;
this.eTime = null;
this.tTime = 0;
};
timerCount.prototype = {
start: function(eleId) {
this.sTime = new Date();
tTime = 0;
$Timer = $(eleId);
TimerLoop();
return this;
},
stop: function() {
this.eTime = new Date();
this.tTime = tTime; //記錄本次總共花費的秒數
clearTimeout(funId);
return this;
},
getStartTime: function() {
return new DateFormat().format(this.sTime);
},
getStopTime: function() {
return new DateFormat().format(this.eTime);
},
getDuration: function() {
//return getDateDiff(this.eTime, this.sTime);
return this.tTime;
}
};
var tTime = 0;
$Timer = $("callTime");
var funId = null;
/**
* 計時器,每秒執行一次
*/
function TimerLoop() {
var hour = parseInt(tTime / 3600); // 小時數
var min = parseInt(tTime / 60); // 分鐘數
if (min >= 60) {
min = min % 60;
}
var lastsecs = tTime % 60;
tTime++;
var str = hour + "時" + min + "分" + lastsecs + "秒";
$Timer.text(str);
funId = setTimeout("TimerLoop()", 1000);
};</span>