首页 > 解决方案 > javascript timer 每次重置和重新运行时都会将时间值加倍

问题描述

我正在启动一些javascript项目,我发现这个计时器有一些困难第一个问题是停止按钮不起作用,我尝试了很多代码但没有任何效果,然后每次我点击重置而不是从1到2到3它1 然后 2 和 4 然后 8 依此类推

var timer = document.querySelector("#timer");
var start = document.querySelector("#start");
var pause = document.querySelector("#stop");
var stop = document.querySelector("#stop");



var time_stopped = true;
var hours = 0;
var minutes = 0;
var seconds = 0;




function start_timer() {
    if (time_stopped == true){
        time_stopped = false;
        cycle();
    }
    console.log("timer started!");
    pause.style.display = "unset";
}

function stop_timer() {
    if (stop_timer == false) {
        stop_timer = true;

    }
    console.log("time stopped!");
    pause.style.display = "none";



}

function restart_timer() {
    timer.innerHTML = "00 00 00";
    hours = 0;
    minutes = 0;
    seconds = 0;
    time_stopped = true;
    cycle();

}

function cycle() {

    
    if (time_stopped == false) {
        hours = parseInt(hours);
        minutes = parseInt(minutes);
        seconds = parseInt(seconds);

        seconds = seconds + 1;


        if (seconds == 60) {
            minutes += 1;
            seconds = 0;
        }

        if (minutes == 60) {
            hours += 1;
            minutes = 0;
        }



        if (seconds < 10 || seconds == 0) {
            seconds = "0" + seconds;
        }

        if (minutes < 10 || minutes == 0) {
            minutes = "0" + minutes;
        }

        if (hours < 10 || hours == 0) {
            hours = "0" + hours;
        }




        timer.innerHTML = `${hours}:${minutes}:${seconds}`;
        setInterval(cycle,1000);

    }
}

这是html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>stopwatch (timer)</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div>

    <div id="timer">
        
            00:00:00
        
    </div>
    <ul>
        <button id="start" onclick="start_timer()">start</button>
        <button id="stop" onclick="stop_timer()">stop</button>
        <button id="restart" onclick="restart_timer()">restart</button>
    </ul>
    </div>


    <script src="script.js"></script>
</body>
</html>

标签: javascriptcssfunctionweb

解决方案


该函数setInterval不仅设置了一个超时事件,还设置了它们的重复时间表。

因此,正如评论中所指出的,每次您打电话时,cycle()您都会创建一个额外的计时器计划,从而使它们在每个间隔有效地加倍。

要解决此问题,您需要更改为setTimeout而不是 set Interval,或者clearInterval在您拨打新电话之前setInterval拨打电话(或者什么都不做,因为setInterval已经为您重复了)。该文档解释了所有这些功能:https ://javascript.info/settimeout-setinterval


推荐阅读