用 setInterval方法可以以指定的间隔实现循环调用函数,直到clearInterval方法取消循环
用clearInterval方法取消循环时,必须将setInterval方法的调用赋值给一个变量,然后clearInterval方法引用该变量。
<script type="text/javascript"> var n = 0; function print(){ document.writeln(n); if(n==1000){ window.clearInterval(s); } n++; } var s = window.setInterval(print, 10); </script>
用setTimeout和clearTimeout完成延时调用,在指定的延迟时间之后运行指定函数,只执行一次。clearTimeout的用法同clearInterval方法的用法相同。
<script type="text/javascript"> function printTime(){ var time = new Date(); var year = time.getFullYear(); var month = (time.getMonth())+1; var daynum = time.getDay(); var hour = time.getHours(); var min = time.getMinutes(); var sec = time.getSeconds(); var da = time.getDate(); var daystr; switch(daynum){ case 0: daystr="星期日"; break; case 1: daystr="星期一"; break; case 2: daystr="星期二"; break; case 3: daystr="星期三"; break; case 4: daystr="星期四"; break; case 5: daystr="星期五"; break; case 6: daystr="星期六"; break; default: daystr=""; } var str = year+"年"+month+"月"+da+"日 "+daystr+" "+hour+": "+min+": "+sec; document.getElementById("t").innerHTML = str; window.setTimeout(printTime, 1000); } </script> <body onload="printTime()"> <br/> <div id="t"></div> </body>