会话长度是定时器的开始时间,默认为25. isEven用于启动/停止定时器,如果isEven为false,定时器应该启动,如果是奇数则应该命中clearInterval,由于某种原因没有停止执行tick()函数(它会使计时器倒计时)。
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
var myVar = setInterval(tick, 1000);
if (isEven == false) {
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--;
seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML =
"0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
clearInterval(myVar);
}
};
答案 0 :(得分:0)
将tick()
函数声明移到if
块
答案 1 :(得分:0)
setInterval变量是本地变量。因此,每次拨打countdown
。解决方案是在函数myVar
之外初始化countdown
或使其成为这样的全局变量:
window.myVar =setInterval (tick,1000);
您还必须将此指令放在第一个if
块中,以便每次都不会被覆盖
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
if (isEven == false) {
window.myVar = setInterval(tick, 1000);
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--; seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML = "0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
if (window.myVar){
clearInterval(window.myVar);
window.myVar = null;
}
}
};