做過彩票、拍賣、活動報名這類專案的人,大概都寫過倒數計時。以排列五這類玩法為例,使用者開啟頁面的瞬間,伺服器會回傳一個 remaintime(本期剩餘秒數),前端要做的就是把這個數字每秒遞減畫出來,歸零時再提示已截止。
把秒數換算成時、分、秒三個欄位,用 setInterval 每秒更新一次;每次更新前先判斷是否已歸零,若是則清除計時器並執行回呼函式。整個過程包成一個建構函式,讓呼叫端只需傳入容器 ID、剩餘秒數與完成後的回呼。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>倒數計時 Demo</title>
<style type="text/css">
em { color: #f00; }
</style>
</head>
<body>
<div id="remaintime"></div>>
<script type="text/javascript">
var TheTime = function () {
this.init.apply(this, arguments);
};
TheTime.prototype = {
init: function (obj) {
var that = this;
obj = that.buildParam(obj);
that.callback = obj.callback;
var container = that.container = document.getElementById(obj.container);
container.innerHTML = '<em></em>小時<em></em>分鐘<em></em>秒';
var hourSpace = that.hourSpace = container.getElementsByTagName('em')[0];
var minuteSpace = that.minuteSpace = container.getElementsByTagName('em')[1];
var secondSpace = that.secondSpace = container.getElementsByTagName('em')[2];
// 已經截止,直接顯示提示
if (obj.remaintime == 0) {
that.resetTime();
return;
}
// 秒數換算為時、分、秒
that.hours = Math.floor(obj.remaintime / 3600);
that._remainder1 = obj.remaintime % 3600;
that.minutes = Math.floor(that._remainder1 / 60);
that.seconds = that._remainder1 % 60;
var timer = that.timer = setInterval(function () {
that.renderTime.apply(that);
}, 1000);
},
buildParam: function (obj) {
obj = {
container: obj.container || 'container', // 容器元素 id
remaintime: Number(obj.remaintime) || 0, // 剩餘秒數
callback: obj.callback || new Function // 倒數結束後的回呼
};
return obj;
},
resetTime: function () {
var that = this;
that.container.innerHTML = "已經截止";
},
// 每秒刷新顯示
renderTime: function () {
var that = this;
if (that.seconds > 0) {
that.seconds--;
} else {
that.seconds = 59;
if (that.minutes > 0) {
that.minutes--;
} else {
that.minutes = 59;
if (that.hours > 0) {
that.hours--;
}
}
}
// 全部歸零,執行回呼
if (that.hours == 0 && that.minutes == 0 && that.seconds == 0) {
that._callback();
}
var bitHandle = that.bitHandle;
that.hourSpace.innerHTML = bitHandle(that.hours);
that.minuteSpace.innerHTML = bitHandle(that.minutes);
that.secondSpace.innerHTML = bitHandle(that.seconds);
},
// 補零,確保一律顯示兩位數
bitHandle: function (num) {
var str = num.toString();
if (str.length < 2) {
str = 0 + str;
}
return str;
},
_callback: function () {
var that = this;
clearInterval(that.timer);
that.callback();
}
};
new TheTime({
container: 'remaintime', // 容器 id
remaintime: 10000, // 伺服器回傳的剩餘秒數
callback: function () {
document.getElementById('remaintime').innerHTML = '已截止';
}
});
</script>
</body>
</html>
把 container、remaintime、callback 的預設處理收到同一個方法裡,init 主流程就能保持乾淨,也方便日後擴充新參數。
不補零的話會出現「9小時3分鐘5秒」這種參差畫面,補成 09:03:05 視覺上穩定得多。
計時器不主動清除會持續佔用資源,這是新手最常漏的一步。
以「每秒遞減計數」為基礎的寫法,在背景分頁被瀏覽器節流時可能產生累積誤差。若對精度有要求,建議改成記錄目標時間戳記,每次 render 都用「目標時間 − 現在時間」重新計算,這樣即使中途被掛起也能自動校正。