setInterval和clearInterval

时间:2013-06-15 18:08:37

标签: javascript

我正在尝试做简单的点击计时器。但我做错了什么,我的clearInterval不起作用。计数进行和清除间隔不起作用。

<!DOCTYPE html>
<html lang="en"> 
    <head>
    <script>
    var seconds = 10;
    var clicks = 0;
    var a=0;
    function start()
    {
        a++;
        if(a > 0 && a < 2)
        {
        var interval;
            if(minute == 0)
            {
                clearInterval(interval) 
                a++;
            }
            else
            {
                interval = setInterval(function(){
                seconds--;
                document.getElementById("time").innerHTML = seconds;
                    },1000);
            }
        }

    }


    function goClick()
    {
        if(a==1)
        {
        clicks++;
        document.getElementById("span").innerHTML = clicks;
        }
    }
    </script>
        <meta charset='utf-8'> 
        <title> Try to find </title>
    </head>
    <body>
        <h1 align="center">how many clicks you can do for 10 seconds </h1>
        <button onclick="start();" >start </button> <br />
        <button onclick="goClick();" >click </button> <br />
        <div><p> count : <span id="span"></span> </p></div>
         <br />
        <div><p> time : <span id="time"></span> </p></div>

    </body>
</html>

1 个答案:

答案 0 :(得分:4)

当前的问题是区间取消部分放在永远不会运行的地方。把它放在区间函数本身:

var interval = setInterval(function(){
    seconds--;
    document.getElementById("time").innerHTML = seconds;    
    if( seconds === 0 ) {
        clearInterval( interval );
    }
},1000);