定时循环

来源:互联网 发布:java编程思想 mobi 编辑:程序博客网 时间:2024/05/18 01:19

问题引出:

当你用动态HTML让什么东西缓缓地在屏幕上移动时,就执行
一个定时循环:“轻轻移动一点,等待,再移动一点,再等
待.....如此这般”

 

错误做法:

<html>
<head>
<script>
function theTimer()
{
 the_time = 0;
 hellIsHot = true;
 
 while (hellIsHot == true)
 {
  the_time += 2;
  var timer = setTimeout("changeTextBoxTo

(the_time);", the_time*1000);
 }

}
function changeTextBoxTo(the_time){
 document.timeclock.value=the_time;
}
</script>
</head>
<body onload="theTimer()">
<input type="text" name="timeclock"/>
</body>
</html>

当在循环里时,
你的浏览器就无法做任何其它的事情,基本上就是停止,执
行动作,再设定下一个定时器,一直到永远。第二,每次设
setTimeout时,浏览器 都要记住你预定执行的内容以及
何时执行。最终你的浏览器会把内存耗尽,这时你的浏览器
会崩溃,或者你的计算机会崩溃,
或者把你弄疯而永远也不
想再写一行Javascript程序了。

 

正确做法:

<html>
<head>
<script>
var the_time = 0;
function theTimer()
{
 document.getElementById("timeclock").value=the_time+"";
 the_time += 2;
 setTimeout("theTimer();",the_time*1000);
}
</script>
</head>
<body onload="theTimer()">
<input type="text" name="timeclock" id="timeclock"/>
</body>
</html>