頁面上想放一個會自己走動的時鐘,示範「今天是幾月幾日星期幾、現在幾點幾分幾秒」,做法非常單純:組出字串寫入元素,再用 setTimeout 每秒呼叫自己一次。
function CurentTime(divID){ var curTime=new Array(); var now=new Date(); var week=['日','一','二','三','四','五','六']; var year=now.getFullYear(); //年 var month=now.getMonth()+1; //月 var day=now.getDate(); //日 var hh=now.getHours(); //時 var mm=now.getMinutes(); //分 var sc=now.getSeconds(); //秒 var wk=now.getDay(); //周 curTime['year']=year; curTime['month']=month<10?'0'+month:month; curTime['day']=day<10?'0'+day:day; curTime['hh']=hh<10?'0'+hh:hh; curTime['mm']=mm<10?'0'+mm:mm; curTime['sc']=sc<10?'0'+sc:sc; curTime['wk']='星期'+week[wk]; curTime=curTime['year']+'年'+curTime['month']+'月'+curTime['day']+'日'+' '+curTime['wk']+' '+curTime['hh']+':'+curTime['mm']+':'+curTime['sc']; document.getElementById(divID).innerHTML='今天是:'+curTime; setTimeout('CurentTime(\''+divID+'\')',1000); }
假設頁面上有一個 id 為 time 的容器:
<script language="javascript">CurentTime('time');</script>
月份要加 1,因為 getMonth() 回傳的是 0 到 11。星期則是用 getDay() 當索引去查表,0 代表週日。補零那串三元運算式是為了讓 9 顯示成 09,視覺上整齊許多。
最後一行用 setTimeout 傳字串的方式呼叫自己,這是舊式寫法;字串形式會走 eval 路徑,建議改成直接傳函式並把 divID 以參數帶入,例如 setTimeout(CurentTime, 1000, divID),既安全也更清晰。另外 setInterval 看似更直覺,但它不保證每次都在上一次完成後才觸發,遇到主執行緒忙碌時容易堆積,因此遞迴 setTimeout 反而是計時器類需求的較佳選擇。
若只需要「顯示目前時間」,也可以善用 Intl.DateTimeFormat,它能自動處理本地化格式與時區,省去自己拼字串的工夫:
const fmt = new Intl.DateTimeFormat('zh-TW', { dateStyle: 'full', timeStyle: 'medium' }); function tick() { document.getElementById('time').textContent = fmt.format(new Date()); } setInterval(tick, 1000);