用setTimeout和clearTimeout完成延时调用,在指定的延迟时间之后运行指定函数,只执行一次。clearTimeout的用法同clearInterval方法的用法相同。
<script type="text/javascript">
function printTime(){
var time = new Date();
var year = time.getFullYear();
var month = (time.getMonth())+1;
var daynum = time.getDay();
var hour = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds();
var da = time.getDate();
var daystr;
switch(daynum){
case 0: daystr="星期日";
break;
case 1: daystr="星期一";
break;
case 2: daystr="星期二";
break;
case 3: daystr="星期三";
break;
case 4: daystr="星期四";
break;
case 5: daystr="星期五";
break;
case 6: daystr="星期六";
break;
default: daystr="";
}
var str = year+"年"+month+"月"+da+"日 "+daystr+" "+hour+": "+min+": "+sec;
document.getElementById("t").innerHTML = str;
window.setTimeout(printTime, 1000);
}
</script>
<body onload="printTime()">
<br/>
<div id="t"></div>
</body>