简体   繁体   中英

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

I'm attempting to build my own timer which resets back to 7 minutes upon clicking the nextTeam button. However, the timer is overlapping itself upon each call instead of resetting. This causes the timer to flip back and forth between displayed times for each function call.

Any advice for a fix would be greatly appreciated!

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);
};

You are creating multiple intervals running at the same time. When you reset the interval you need to call clearInterval() on the value returned by setInterval . An easy way to do it is to create a variable outside the scope of the functions and save the interval handle there.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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