3 回答

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

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
您無(wú)需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貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為您不需要添加更多代碼,您只需要像這樣簡(jiǎn)化它
var count = 3;
function startTimer() {
const timer = setInterval(function () {
document.getElementById("target").innerText = count;
count--;
if (count <= 0) {
clearInterval(timer);
ranCoord();
}
}, 1000)
}
添加回答
舉報(bào)