3 回答

TA貢獻1801條經驗 獲得超8個贊
如果在 startTimer 函數中聲明了 count 變量,則計時器的每次迭代都將覆蓋其計數值,因此不會倒計時。
setInterval無限重復其功能,因此只需要在循環外調用一次,而不是setTimeout只運行一次并且每次迭代都需要調用。
另一種使用方法setTimeout是:
function startTimer(count) {
if (count <= 0) {
ranCoord();
} else {
document.getElementById("target").innerText = count;
setTimeout(function() { startTimer(--count); }, 1000);
}
}
此版本還通過將剩余計數作為參數傳遞來避免使用全局變量。

TA貢獻1821條經驗 獲得超6個贊
您無需startTimer致電setInterval
var count = 3;
function startTimer() {
var timer = setInterval(function() {
if (count === 0) {
clearInterval(timer);
ranCoord(); //function to run when timer hits zero.
} else {
document.getElementById("target").innerText = count;
count--;
}
}, 1000);
}
function ranCoord() {
console.log("Timer hit 0")
}
img {
height: 100px;
width: 100px;
outline: 1px solid blue;
}
<div class="start">
<img src="images/start-default.png" onclick="startTimer();" />
</div>
<div id="target"></div>

TA貢獻1846條經驗 獲得超7個贊
我認為您不需要添加更多代碼,您只需要像這樣簡化它
var count = 3;
function startTimer() {
const timer = setInterval(function () {
document.getElementById("target").innerText = count;
count--;
if (count <= 0) {
clearInterval(timer);
ranCoord();
}
}, 1000)
}
添加回答
舉報