一个计时器问题?
一个偶然的发现,希望能有高手帮忙解答!
这个计数器原本是设置每一秒更新自动加1的,可是当连续多次点击“开始计时”按钮之后,发现情况就变了。程序根据你点击的次数多少而改变。
比如你点了2次,那程序就每一秒自动加2;如果连续点了10次,那就变成每一秒自动加10了。如果你接着又多次点击“停止计时”按钮;会发现每秒增加的数字又变少了,点多少次就减少多少;
当你点击的次数大于等于“开始计时”按钮的时候。计时又正常了!想来想去想不明白是什么原因导致这样的。又应该如何解决呢?期待高手的解答!
谢谢!下面是完整的代码:<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}function stopCount()
{
clearTimeout(t)
c=0
}
</script>
</head><body><form>
<input type="button" value="开始计时!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="停止计时!" onClick="stopCount()">
</form><p>请点击上面的“开始计时”按钮来启动计时器。输入框会一直进行计时,从 0 开始。点击“停止计时”按钮可以终止计时。</p></body></html>

解决方案 »

  1.   

    var c=0
    var t 
    都是window下的变量,你的函数引用的都是同一个变量。
    timedCount()多次被递归调用,累加的都是c,所以会越来越快.
      

  2.   


    <html> 
    <head> 
    <script type="text/javascript"> 
    var c=0 
    var t 
    function timedCount() 
    {
    if(t!=null){clearTimeout(t);t=null;} 
    document.getElementById('txt').value=c 
    c=c+1 
    t=setTimeout("timedCount()",1000) 
    } function stopCount() 

    if(t!=null){clearTimeout(t);t=null;} 
    c=0; 

    </script> 
    </head> <body> <form> 
    <input type="button" value="开始计时!" onClick="timedCount()"> 
    <input type="text" id="txt"> 
    <input type="button" value="停止计时!" onClick="stopCount()"> 
    </form> <p>请点击上面的“开始计时”按钮来启动计时器。输入框会一直进行计时,从 0 开始。点击“停止计时”按钮可以终止计时。 </p> </body> </html> 
      

  3.   

    <html> 
    <head> 
    <script type="text/javascript"> 
    var c=0 
    var t 
    function timedCount(p) 
    {
    if(p && t>0)
    {
    return false;
    }
    document.getElementById('txt').value=c; 
    c=c+1; 
    t=setTimeout("timedCount(false)",1000);
    } function stopCount() 

    clearTimeout(t);
    t=0;
    c=0;

    </script> 
    </head> <body> <form> 
    <input type="button" value="开始计时!" onClick="timedCount(true)"> 
    <input type="text" id="txt"> 
    <input type="button" value="停止计时!" onClick="stopCount()"> 
    </form>