我正在尝试构建一个简单的倒计时应用程序。是否可以在 setTimeout 上显示计时器值,还是必须使用 for 循环?
谢谢!
与setTimeout
:
var n = 100;
setTimeout(countDown,1000);
function countDown(){
n--;
if(n > 0){
setTimeout(countDown,1000);
}
console.log(n);
}
或使用setInterval
:
var n = 100;
var tm = setInterval(countDown,1000);
function countDown(){
n--;
if(n == 0){
clearInterval(tm);
}
console.log(n);
}
<script>
var timer = setInterval("mytimer()",1000);
seconds = 0;
function mytimer()
{
document.getElementById("div_timer").innerHTML = seconds; // this is the same as $("div_timer").html(timer) in jquery.
seconds++;
}
</script>
<body>
<div id="div_timer"></div>
</body>