繁体   English   中英

为什么多次调用时,我的window.setInterval函数在DOM中会自身重叠?

[英]Why is my window.setInterval function overlapping itself in the DOM when called multiple times?

我正在尝试构建自己的计时器,在单击nextTeam按钮时,该计时器会重置为7分钟。 但是,计时器在每次调用时都会重叠,而不是进行重置。 这将导致计时器在每个函数调用的显示时间之间来回切换。

任何修复建议都将不胜感激!

HTML:

<div>
    <div id="clock"><span id="minutes">7</span>:<span id="seconds">00</span></div>
    <button id="nextTeam"onclick="showNextTeam()" type="button">next team</button>  
</div>

JS:

function showNextTeam() {
    clock(7, 0);
}

var clock = function(minutes, seconds) {
    window.setInterval(() => {
        seconds--
        if (seconds < 0) {
            minutes--;
            seconds = 59;
        }

        document.getElementById("minutes").textContent = minutes;

        if (seconds < 10) {
            document.getElementById("seconds").textContent = "0" + seconds;
        }
        else {
            document.getElementById("seconds").textContent = seconds;
        }
    }, 1000);
};

您正在创建同时运行的多个时间间隔。 重置间隔时,需要对setInterval返回的值调用clearInterval() 一种简单的方法是在函数范围之外创建一个变量,并将间隔句柄保存在那里。

 let interval; function showNextTeam() { clock(7, 0); } var clock = function(minutes, seconds) { clearInterval(interval) //clear the old one first interval = window.setInterval(() => { seconds-- if (seconds < 0) { minutes--; seconds = 59; } document.getElementById("minutes").textContent = minutes; if (seconds < 10) { document.getElementById("seconds").textContent = "0" + seconds; } else { document.getElementById("seconds").textContent = seconds; } }, 1000); }; 
 <div> <div id="clock"><span id="minutes">7</span>:<span id="seconds">00</span></div> <button id="nextTeam"onclick="showNextTeam()" type="button">next team</button> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM