1.setTimeout(表达式,time),示例代码如下:
<html>
<head>
<script type="text/javascript">
function test(){
//var date = new Date();
//alert(date);
//setTimeout(getServerTime,1000);
setTimeout("alert('aaa')",2000);
}
</script>
</head>
<body>
<button type="button" οnclick="test()">date</button>
</body>
</html>
在等待两秒后,会弹出一个对话框,但只会按一次按钮alert一次。
2.setTimeout(无参的function,time),示例代码如下:
<html>
<head>
<script type="text/javascript">
function test(){
var date = new Date();
alert(date);
setTimeout('test()',1000);(双引号也可以)
//还有下面这种写法,不带括号也不用带单引号或双引号
//setTimeout(test,1000);
}
</script>
</head>
<body>
<button type="button" οnclick="test()">date</button>
</body>
</html>
按一次按钮后,每隔一秒钟就会alert一次。
3.setTimeout(带参数的function,time),示例代码如下:
<html>
<head>
<script type="text/javascript">
var date = new Date();
var val = date.getTime();
function test(id){
val += 1000;
var currDate = new Date(val);
if(id == null){
document.getElementById(id).value = null;
}else{
var y = currDate.getFullYear();
var m = currDate.getMonth()+1;
var d = currDate.getDate();
var hh = currDate.getHours();
var mi = currDate.getMinutes();
var ss = currDate.getSeconds();
if(m<10){m="0"+m;}
if(d<10){d="0"+d;}
if(hh<10){hh="0"+hh;}
if(mi<10){mi="0"+mi;}
if(ss<10){ss="0"+ss;}
document.getElementById(id).value = y + "-" + m + "-" + d + " "
+hh + ":" + mi + ":" + ss;
}
setTimeout(function (){test(id);},1000);
}
</script>
</head>
<body>
<input type="text" id="testTime" value=""/><script type="text/javascript">test('testTime');</script>
</body>
</html>
这种常用于每秒递增显示客户端时间。
由于本人才接触javascript,了解的不多。。这些只是个人经验。。可能会有错误。。望大家批评指正。。