setInterval 每秒更新一次畫面時:分:秒 格式顯示<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>網頁停留時間</title>
<style>
#stay-time {
display: inline-block;
padding: 8px 16px;
background: #2c3e50;
color: #ecf0f1;
border-radius: 4px;
font-family: 'Consolas', 'Monospace';
font-size: 1.2rem;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}
</style>
</head>
<body>
<h2>您已停留:</h2>
<div id="stay-time">00:00:00</div>
<script>
(function() {
let seconds = 0;
const display = document.getElementById('stay-time');
function formatTime(sec) {
const h = String(Math.floor(sec / 3600)).padStart(2, '0');
const m = String(Math.floor((sec % 3600) / 60)).padStart(2, '0');
const s = String(sec % 60).padStart(2, '0');
return `${h}:${m}:${s}`;
}
function tick() {
seconds++;
display.textContent = formatTime(seconds);
}
// 每 1000ms 執行一次
const timerId = setInterval(tick, 1000);
// 頁面卸載時清理
window.addEventListener('beforeunload', () => clearInterval(timerId));
// 可選:頁面隱藏時暫停(Document Visibility API)
document.addEventListener('visibilitychange', () => {
if (document.hidden) clearInterval(timerId);
else timerId = setInterval(tick, 1000); // 重新啟動
});
})();
</script>
</body>
</html>
| API | 用途 |
|---|---|
setInterval(fn, ms) | 每隔 ms 毫秒重複執行 fn,回傳 timerId |
clearInterval(timerId) | 停止對應的週期性執行 |
String.padStart(len, '0') | 補零對齊,ES2017,現代瀏覽器皆支援 |
visibilitychange | 偵測分頁切換/最小化,可選擇暫停計時 |
let idleTimer;
function resetIdle() {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => clearInterval(timerId), 30000); // 30秒無動作停止
}
['mousemove','keydown','click','scroll'].forEach(evt =>
document.addEventListener(evt, resetIdle)
);
window.addEventListener('beforeunload', () => {
clearInterval(timerId);
navigator.sendBeacon('/api/stay-time', JSON.stringify({duration: seconds}));
});
sendBeacon 非同步、不阻塞卸載、可靠送達,適合統計場景。
hidden 狀態,上述 visibilitychange 邏輯會自動暫停。