setInterval()出错

时间:2017-08-17 14:20:48

标签: javascript setinterval

我正在创建一个带有setInterval的秒表,如下所示:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Stopwatch</title>
        <link href="https://fonts.googleapis.com/css?family=Saira" rel="stylesheet">
        <link href="stopwatch.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
    </head>
    <body>
        <div class="but">
        <h1>Stopwatch</h1>
            <p id="timer">0</p>
            <button id="start">Start/Stop</button>
            <button id="reset">Reset</button>
            <button id="record">Record Time</button>
        </div>
    <script src="stopwatch.js"></script>
    </body>
</html>

和JavaScript文件:

var timer = document.getElementById("timer");
var sec = 0;
var on = false;
var interval;
//execution
document.getElementById("start").addEventListener("click", startStop);
//function
function startStop(){
    if(on == false){
        counter();
        on = true;
    }else if(on == true){
        clearInterval(interval);
        on = false;
    }
}

function counter(){
    interval = setInterval(time, 1000);
}

function time(){
    sec += 0.01;
    timer.innerHTML = sec;
}

我将间隔设置为1000来测试它。它在前5秒运行良好,但在第6秒,显示的数字是0.060000000000000005,而第9,10,11也没有效果。有人可以帮我解决这个问题吗?

0 个答案:

没有答案