日期:2014-05-16  浏览次数:20356 次

js中settimeout函数的问题
今天写了个js定时器的问题:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css"/>
<script language="javascript">
window.onload=function(){
var t=null;
var i=0;
function a(){
 i++;
 console.log(i);
 if(i==20){
  clearTimeout(t);
 }
 t=setTimeout(a,10);
}
a();
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
这样一个函数,在火狐下,输出到32,在ie和chrome下会一直执行。为什么?分析一下原因。
而在下面这个程序中,点击“end"为什么可以彻底关掉定时器。
<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",100)
}
function stopCount()
{
clearTimeout(t)
}
</script>
</head>
<body>
<form>
<input type="button" value="start" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="end" onClick="stopCount()">
</form>
</body>
</html>
为什么?第一个函数明显没有关掉定时器,第二个程序定时器没有关掉。
js settimeout 定时器

------解决方案--------------------
一。我测试程序一firefox下也是不停的。
二。程序一,你中断了一个timeout,但又马上生成了一个新的timeout,所以不会停。

window.onload=function(){
var t=null;
var i=0;
function a(){
i++;
console.log(i);
if(i==20){
clearTimeout(t);//清除了上一个timeout,但这个timeout事实上已经执行了,就是目前运行到的这个,clearTimeout只是不执行,对已经执行的没有作用。
}
t=setTimeout(a,10);//又生成了一个新的timeout
}
a();
}


------解决方案--------------------
你看错了,火狐下也是一样的,你可以将代码中的 console.log(i);换成document.getElementById("div1").innerHTML = i;就能清楚的看到结果了,估计你是看到firebug中的控制台只输出了前32行吧,下面是几张截图,对比一下:)



------解决方案--------------------
if(i==20){
  clearTimeout(t);
  return;
 }

加一个return就行了,原因应该不用解释了。