近期在開發排列五的彩票專案,每一期都有購彩時段。使用者打開頁面時,伺服器會傳來一個 remaintime(距本期結束的剩餘秒數),接著這個數字要在用戶端持續遞減呈現,讓使用者即時掌握本期剩餘時間。
實現原理並不複雜,但把細節處理好才是關鍵:位數補零、邊界判斷、倒數歸零後的回呼,以及避免計時器游離。以下是一個完整的可複用實作。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>index</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>
buildParam 統一處理預設值與型別轉換,讓後續邏輯不必到處寫 if 判斷。init 開頭用 var that = this 存下參照,因為 setInterval 的回呼會失去原本的 this 綁定。若使用 ES6 箭頭函數,這個問題會自動消失。bitHandle 確保顯示為 09 而非 9,視覺上更穩定,不會產生左右位移。clearInterval,否則計時器會永遠空轉消耗資源。這個結構的優點是易於複用:換一個容器 id、換一份 remaintime,就能在任何頁面搭出倒數元件。若要更進一步,可以把它改成接收時間戳而非秒數,並以「目標時間減當前時間」的方式每次重算,這樣即使頁面被切到背景導致計時器被瀏覽器節流,回來時顯示的數字仍然正確。