2 回答
TA贡献1821条经验 获得超4个赞
您需要将您的存储setTimeout()在变量中。匿名超时无法清除。
var timeout;
function countdown(elementName, minutes, seconds) {
var element, endTime, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
element.innerHTML = "00:00";
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = twoDigits(time.getUTCMinutes()) + ':' + twoDigits(time.getUTCSeconds());
timeout = setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}
element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
stopTimer();
}
function stopTimer() {
clearTimeout(timeout);
}
countdown("countdown", 0, 30);
TA贡献1911条经验 获得超7个赞
您需要设置一个全局变量等于 的返回值setTimeout(...),然后将该全局变量传递给clearTimeout()func。
就是这样:
let tm;
function countdown(elementName, minutes, seconds) {
var element, endTime, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}
function stopTimer(t) {
return clearTimeout(t);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
element.innerHTML = "00:00";
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = twoDigits(time.getUTCMinutes()) + ':' + twoDigits(time.getUTCSeconds());
tm = setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}
element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
return stopTimer(tm);
}
countdown("countdown", 0, 30);
添加回答
举报