記錄頁面加載時間戳,定時器每秒計算差值並格式化為「分:秒」顯示,常用於統計用戶閱讀時長、防刷時長驗證。
var startTime = new Date().getTime(); // 頁面載入瞬間
function getTimeSpent() {
return Math.round((new Date().getTime() - startTime) / 1000); // 秒數
}
function formatTime(seconds) {
var m = Math.floor(seconds / 60);
var s = seconds % 60;
return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
}
function showSecs() {
var total = getTimeSpent();
document.getElementById('timeDisplay').value = formatTime(total);
setTimeout(showSecs, 1000);
}
// 頁面卸載時上報
window.onbeforeunload = function() {
var stayed = getTimeSpent();
// navigator.sendBeacon('/api/stay', 'time=' + stayed); // 異步上報不阻塞
};
<input type="text" id="timeDisplay" readonly style="border:none;background:transparent;">
<script> showSecs(); </script>
頁面最小化/切換標籤頁時不計時,使用 Page Visibility API:
var visibleStart = Date.now(), total = 0;
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
total += Date.now() - visibleStart;
} else {
visibleStart = Date.now();
}
});
function getActiveTime() {
return total + (document.hidden ? 0 : Date.now() - visibleStart);
}
setTimeout 非精確 1 秒,長時間運行會有誤差,關鍵業務請用 Date.now() 差值計算而非遞增計數器。navigator.sendBeacon 確保頁面關閉時也能發送。