下面是简单时间显示代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>当前系统时间</title>
<link rel="stylesheet" href="style.css" />
<script language="javascript" type="text/javascript">
window.onload = function(){
showTime();
}
function checkTime(i){ //补位处理
return i < 10 ? "0" + i : i;
}
function showTime(){
var now=new Date();
var year= now.getFullYear();
var month= now.getMonth() + 1;
var day= now.getDate();
var h= now.getHours();
var m= now.getMinutes();
var s= now.getSeconds();
h=checkTime(h)
m=checkTime(m)
s=checkTime(s)
var weekday=new Array(7)
weekday[0]="星期日"
weekday[1]="星期一"
weekday[2]="星期二"
weekday[3]="星期三"
weekday[4]="星期四"
weekday[5]="星期五"
weekday[6]="星期六"
document.getElementById("show").innerHTML= year+"年"+month+"月"+day+"日 "+ " " +h+":"+m+":"+s;
t=setTimeout('showTime()',500)
}
</script>
</head>
<body>
<div class="content1">
<div id="show">显示时间的位置</div>
</div>
</body>
</html>
如果把setTimeout设置成1000会比实际时间慢一秒,这是为什么呢?
t=setTimeout('showTime()',500);
setTimeout函数设置的延时n毫秒,JS单线程执行以及事件循环机制(EventLoop)并不能保证精确的在n毫秒后执行回调,只能保证至少在n毫秒后才能有机会被执行~~~~;
基于以上的JS实现,如果你想要接近于需要的时间执行,就想要减小时间颗粒度,比如你想要1000毫秒间隔,那就设置500ms,但是这个还是不精确的~~~