我想做一个从10秒到1秒的倒计时。当前的secondindex应该打印在div-tag中。但是它没有显示数字,而是进入了函数。而且它没有结束,所以它进入了一个永无止境的。
`
var myCountdown = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
setInterval(timer(), 1000);
timer = () => {
for(i = 0; i < myCountdown.length; i++){
console.log(myCountdown[i]);
document.getElementById("test").innerHTML += myCountdown[i];
}}
`
正如Teemu在评论中提到的,你必须停止间隔。
var token = setInterval(timer, 1000); // Set the timer function to run every 1000ms until we tell it to stop.
var element = document.getElementById("test");
var i = 10;
function timer() {
if (i <= 0) {
clearInterval(token); // Stop counting down.
} else {
i -= 1; // Count down.
element.innerHTML = i;
}
}
crystalbit的答案也可以,它只是使用了 setTimeout
而不是 setInterval
.
let i = 10;
const work = () => {
document.getElementById("test").innerHTML = i;
if (i--) setTimeout(work, 1000);
}
work();
试试这个
如果你真的想使用数组,这里有一个解决方案。
const countdown = ['one', 'two', 'three', 'four', 'five']
let timer = setInterval(() => {
if (countdown.length) document.getElementById("test").innerHTML = countdown.shift();
else clearInterval(timer)
}, 1000)
运行这段代码做个演示
const countdown = ['one', 'two', 'three', 'four', 'five']
let timer = setInterval(() => {
if (countdown.length) document.getElementById("test").innerHTML = countdown.shift();
else clearInterval(timer)
}, 1000)
body {
color: #fff;
background:tomato;
display:flex;
justify-content:center;
align-items:center;
}
<h1 id='test'></h1>