setTimeout()与setInterval()两者用法差不多,但是又有区别。
setTimeout(code,millisec) 只执行code一次,如果要多次调用,请使用setInterval()或让code自身再次调用SetTimeout()
setInterval(code,millisec[,"lang"]) 不停的调用函数,直到clearInterval()被调用或关闭
案例一:setTimeout()不会自动重复执行
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1> <font color=blue> haorooms博客示范网页 </font> </h1>
<p> 请等三秒!</p>
<script>
setTimeout("alert('对不起, haorooms博客要你等候多时')", 3000 )
</script>
</body>
</html>
案例二:setTimeout()可以制作网页中的时间跳动
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var x = 0
function countSecond()
{
x = x+1
document.haorooms.haoroomsinput.value=x
setTimeout("countSecond()", 1000)
}
</script>
</head>
<html>
<body>
<form name="haorooms">
<input type="text" name="haoroomsinput"value="0" size=4 >
</form>
<script>
countSecond()
</script>
</body> </html>
案例三:计算在页面的停留时间
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
x=0
y=-1
function countMin()
{ y=y+1
document.displayMin.displayBox.value=y
setTimeout("countMin()",60000)
}
function countSec()
{ x = x + 1
z =x % 60
document.displaySec.displayBox.value=z
setTimeout("countSec()", 1000)
}
</script> </head>
<body>
<table> <tr valign=top> <td> 你在haorooms博客中的停留时间是: </td>
<td>
<form name=displayMin>
<input type=text name=displayBox value=0 size=4 >
</form>
</td>
<td> 分 </td>
<td>
<form name=displaySec> </td>
<td> <input type=text name=displayBox value=0 size=4 >
</form>
</td>
<td> 秒。</td> </tr>
</table>
<script>
countMin()
countSec()
</script>
</body>
</html>
案例四:清除定时器clearTimeout
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
x = 0
y = 0
function count1()
{ x = x + 1
document.display1.box1.value = x
meter1=setTimeout("count1()", 1000)
}
function count2()
{ y = y + 1
document.display2.box2.value = y
meter2=setTimeout("count2()", 1000)
}
</script> </head>
<body>
<p> </br>
<form name="display1">
<input type="text" name="box1" value="0" size=4 >
<input type=button value="停止计时" onClick="clearTimeout(meter1) " >
<input type=button value="继续计时" onClick="count1() " >
</form>
<p>
<form name="display2">
<input type="text" name="box2" value="0" size=4 >
<input type=button value="停止计时" onClick="clearTimeout(meter2) " >
<input type=button value="继续计时" onClick="count2() " >
</form>
<script>
count1()
count2()
</script>
</body>
</html>
案例五 setInterval 要加入jquery showTime这个参数不能使用双引号和括号
<html>
<head>
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
setInterval (showTime, 2000);
function showTime()
{
var today = new Date();
alert("The time is: " + today.toString ());
}
$.extend({
show:function(){
alert("ready");
}
});
setInterval($.show,3000);
})
</script>
</head>
<body>
<div>
<hr>
</div>
</body>
</html>