javascript当中时间控制setTimeout和setInterval的用法
时间控制setTimeout和setInterval
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
马克-to-win:下个例子说明每秒刷新时间如何实现。(利用setTimeout方法):
setTimeout和setInterval的区别是:setTimeout只执行1次,而setInterval可以无限执行。
例 1.9.1(setTimeoutIEFF.html)
<HTML>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<SCRIPT LANGUAGE="JavaScript">
<!--
function time()
{
var now = new Date();
var y = now.getFullYear();
var m = now.getMonth()+1;
var d = now.getDate();
var x = now.getDay();
var hour = now.getHours();
var day =new Array("日","一","二","三","四","五","六");
var xingqi = day[x];
var mi =now.getMinutes();
var s = now.getSeconds();
var t =document.getElementById("t");
t.innerHTML="今天是"+y+"年"+m+"月"+d+"日"+"星期"+xingqi+","+hour+":"+mi+":"+s;
setTimeout("time()",1000);
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="time()">
<div id="t"></div>
</BODY>
</HTML>
setInterval&clearInterval
例 1.9.2(setIntervalTimeoutIEFF.html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<SCRIPT LANGUAGE="JavaScript">
<!--
var n=2;
function startNum()
{
/*马克-to-win:下面这句话可要可不要,如有, 则效果和setIntervalTimeout1.html就一样了, 没有也没事,就是效果不一样, 没有它, 就是不能立即改变了, 只能
过一秒才能改变。*/
addNum();
/*If you only want to delay the execution of some code and you want it to be executed just once, then use the setTimeout() method instead.The setInterval() method establishes a periodically scheduled execution timer that runs the same fragment of script continuously with a delay timer between each cycle.从实验结果上看, setInterval("addNum()",1000)意味着1秒后执行addNum。*/
temp = setInterval("addNum()",1000);
}
function addNum()
{
document.getElementById("num").innerHTML=n;
n++;
}
function stopNum()
{
clearInterval(temp)
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<div id="num">0</div>
<INPUT TYPE="button" value="start" onclick="startNum()"> <INPUT TYPE="button" value="stop" onclick="stopNum()">
</BODY>
</HTML>