时间间隔计时器:
setInterval(代码,交互时间)
代码:需要调用的函数或者要执行的代码串。
交互时间:周期性执行代码的时间间隔(以毫秒为单位)
返回值:claerInterval() 取消代码的周期性执行。
eg:动态的显示 时分秒
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>定时器</title> <script type="text/javascript"> var attime; function clock(){ var time=new Date(); attime= time.getHours()+':'+time.getMinutes()+':'+time.getSeconds(); document.getElementById("clock").value = attime; } var int=setInterval(clock,1000); </script> </head> <body> <form> <input type="text" id="clock" size="50" />
</br>
<input type="button" value="Stop" onclick="clearInterval(int)" />
</form> </body> </html>
一次性计时器:setTimeout("代码",延迟时间)
eg:打开网页3秒后,弹出提示框
<script>
setTimeout("alert('Hello World')",3000);
</script>
eg: 秒表计数器:(递归的调用计数器函数)
<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var num=0,i; function numCount(){ document.getElementById('txt').value=num; num=num+1; i= setTimeout("numCount()",1000); } function stopCount(){ clearTimeout(i); } </script> </head> <body> <form> <input type="text" id="txt" /> <input type="button" value="Start" onClick="numCount()" /> <input type="button" value="Stop" onClick="stopCount()" /> </form> </body> </html>