我在创建JS计时器时遇到问题。当时间结束或手动停止时,该功能继续执行seconds--
,因此即使重置时间,再次启动它也会以两倍的速度开始运行。如何手动停止功能?我试图标记它并使用break label;
但没有取得多大成功。这是我的代码
HTML
<div id="clock-form">
<i class="fa fa-clock-o" aria-hidden="true"></i>
<input type="number" step="10" id="time-minutes" class="time" value="30"><div id="clock-time"></div></div>
<div id="clock-buttons">
<button id="play-button" type="submit" name="play"><i class="fa fa-play clock-buttons" aria-hidden="true"></i></button>
<button id="stop-button" type="submit" name="stop"><i class="fa fa-stop clock-buttons" aria-hidden="true"></i></button>
</div>
JS
window.onload = function() {
if(getCookie("date2")) {
startCountdown();
}
var inputMinutes = document.getElementById("minutes");
var startButton = document.getElementById("play-button");
startButton.onclick = function() {
startCountdown();
}
stopButton = document.getElementById("stop-button");
stopButton.onclick = function() {
delete_cookie("date2");
clearInterval("intervalHandle");
document.getElementById("clock-time").style.display = "none";
document.getElementById("time-minutes").style.display = "inline";
// Stop here?
}
}
function startCountdown() {
var minutes = document.getElementById("time-minutes").value;
if(isNaN(minutes)) {
alert("Por favor, inserir um número");
return;
}
var dateNow = Math.floor(new Date());
if(!getCookie("date2")) {
var dateEnd = (dateNow + (minutes * 60000));
} else {
var dateEnd = getCookie("date2");
}
document.cookie = "date2="+dateEnd;
secondsRemaining = Math.floor((dateEnd - dateNow) / 1000);
intervalHandle = setInterval(tick, 1000);
document.getElementById("time-minutes").style.display = "none";
document.getElementById("clock-time").style.display = "inline";
}
function tick() {
var timeDisplay = document.getElementById("clock-time");
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = "0" + sec;
}
var message = min + ":" + sec;
timeDisplay.innerHTML = "<div style=\"display:inline-block; font-family: 'Open Sans'; font-size:0.9em; font-weight: bold;\">" + message + "</div>";
if(secondsRemaining === 0) {
alert("Time's over");
clearInterval("intervalHandle");
document.getElementById("clock-time").style.display = "none";
document.getElementById("time-minutes").style.display = "inline";
delete_cookie("date2");
// Stop here?
}
secondsRemaining--;
}
我省略了有关cookie的功能。非常感谢大家!
答案 0 :(得分:1)
如果您指的是停止间隔运行的代码,只需拨打clearInterval(intervalHandle)
https://www.w3schools.com/jsref/met_win_clearinterval.asp
我可能完全错了,但我认为您不希望将变量作为字符串传递给clearInterval。而不是致电clearInterval("intervalHandle")
致电clearInterval(intervalHandle)