有些頁面需要每隔一段時間自動更新內容,例如資訊看板或限時頁面。本文分享一個倒數計時並在歸零時自動刷新頁面的 JavaScript 範例。
我們宣告一個變數來保存剩餘秒數,透過 setInterval 每秒觸發一次函數,將秒數減一并更新到頁面上顯示;當秒數歸零時,就呼叫 location.reload() 重新載入整個頁面。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>60刷新本頁</title>
<script type="text/javascript">
var t;
t=60;
function shua(){
t=t-1;
document.getElementById("hints").innerHTML="離下次刷新時間還有 "+t+" 秒";
if (t==0){
document.location.reload();
}
}
</script>
</head>
<body onload="window.setInterval(shua,1000);">
<center>
<font id="hints" style="color:blue">離下次刷新時間還有60秒</font><br/>
<center>
</body>
</html>
把 body 的 onload 事件綁定到 setInterval,即可在頁面載入後立即啟動倒數,操作相當直觀。