首页 > 解决方案 > 为什么我的 window.setInterval 函数在多次调用时会在 DOM 中重叠?

问题描述

我正在尝试构建我自己的计时器,该计时器在单击 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);
};

标签: javascriptfunction

解决方案


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

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>


推荐阅读