javascript - 为什么我的 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);
};
解决方案
您正在创建同时运行的多个间隔。当您重置间隔时,您需要调用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>
推荐阅读
- html - 如何在 freeMarker 中动态访问分配的变量
- jquery - jQuery - 单击并隐藏所有其他元素(不是直接父元素)的切换元素
- download - 使用 ZK 的 `Filedownload.save()` 时如何指定文本/CSV 文件的编码?
- c# - C# - 泛型类中的方法,对 T 有附加约束
- r - 为每个条形图添加一个标签 r
- android-studio - 方法“getExternalFilesDirs”添加到黑名单
- android - 在安卓模拟器中运行系统应用
- docker - 是否可以将 Docker 中的卷视为设备?
- sql - JDBC 批量插入,返回 ID
- javascript - 如何在 javascript 中测试模式正则表达式