我正试图创建一个倒计时时钟,但遇到了一点麻烦。它显示的是最后的数字,也就是for循环的最后结果,这是我不想要的。我的目标是每次循环时,for循环都要启动我的.setTimeout。我希望得到任何帮助。
const countdownClock = (ranNum) => {
const startingNum = ranNum * 50;
for(let i = startingNum; i > 0; i--) {
setTimeout(() => countdownSpan.textContent = [i], 1000);
}
}
这是因为 setTimeout
正在等待 1s
来执行,直到那时,即使在你的第一个 setTimeout
的值,而当你的第一次超时被触发时,你的 i
被更新,现在是循环的最后一个数字。你可以用 promises
和 async/await
.
const countdownClock = async (ranNum) => {
const startingNum = ranNum * 50;
for(let i = startingNum; i > 0; i--) {
await new Promise(resolve => {
setTimeout(() => {
countdownSpan.textContent = [i];
resolve()
}, 1000)
});
}
}
希望对你有所帮助!
定时器功能在当前功能完成后才会启动。这就是为什么你的 for
循环在定时器函数运行之前运行完成。为了看到计时器滴答作响,你根本不应该使用循环,因为计时器会创建循环功能。你只需要一个 setInterval()
或 setTimeout()
是递归的。
const element = document.getElementById("countdown");
let startingNum = parseInt(Math.random() * 50, 10);
let timer = null;
function counter(){
// Clear any running timer to prevent multiple
// timers from stacking up in the event queue
clearTimeout(timer);
startingNum--; // Decrease the counter
// If the count is greater than 0
if(startingNum >-1){
element.textContent = startingNum;
// Set a new timer up to call this function
timer = setTimeout(counter, 1000);
}
}
// Start the process off
timer = setTimeout(counter, 1000);
<div id="countdown"></div>