endTime(毫秒)。setInterval 每秒計算剩餘毫秒數。Math.floor + 取模)。<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.countdown { display: flex; gap: 8px; font-family: monospace; font-size: 1.5rem; }
.countdown span { background: #f5f5f5; padding: 0.2em 0.6em; border-radius: 4px; }
.countdown .unit { display: none; } /* 可選:隱藏單位文字 */
@keyframes pulse { 0%,100% { box-shadow: 0 0 0 transparent; } 50% { box-shadow: 0 0 12px #486aac, 0 0 18px #008cff; } }
.countdown.expired { animation: pulse 1s infinite; }
</style>
</head>
<body>
<div class="countdown" id="cd">
<span id="d">00</span><span class="unit">天</span>
<span id="h">00</span><span class="unit">時</span>
<span id="m">00</span><span class="unit">分</span>
<span id="s">00</span><span class="unit">秒</span>
</div>
<script>
const $ = id => document.getElementById(id);
const endTime = Date.now() + 2 * 24 * 60 * 60 * 1000; // 2 天后
function pad(n) { return String(n).padStart(2, '0'); }
function update() {
const diff = endTime - Date.now();
const root = $('cd');
if (diff > 0) {
const d = Math.floor(diff / 86400000);
const h = Math.floor(diff / 3600000) % 24;
const m = Math.floor(diff / 60000) % 60;
const s = Math.floor(diff / 1000) % 60;
$('d').textContent = pad(d);
$('h').textContent = pad(h);
$('m').textContent = pad(m);
$('s').textContent = pad(s);
root.classList.remove('expired');
} else {
$('d').textContent = $('h').textContent = $('m').textContent = $('s').textContent = '00';
root.classList.add('expired');
}
}
setInterval(update, 1000);
update(); // 立即執行一次避免延遲
</script>
</body>
</html>
requestAnimationFrame 高精度若需亞秒級精度(如毫秒顯示),改用 requestAnimationFrame 迴圈,但 1 秒更新通常 setInterval 即可。
var now = new Date() 後又在 timer() 內重新 new Date(),改用 Date.now() 直接取毫秒數更簡潔。setTimeout 切換 css,改用 CSS @keyframes 交給瀏覽器合成器,效能更好且不阻塞 JS。$('#res').css(),重構為原生 classList,零依賴。倒數計時器核心是「目標時間戳 - 當前時間戳」換算單位。現代寫法:Date.now() + padStart + CSS 動畫,零依賴、易維護、效能佳。