7

我正在尝试构建一个简单的倒计时应用程序。是否可以在 setTimeout 上显示计时器值,还是必须使用 for 循环?

谢谢!

4

2 回答 2

22

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);
}
于 2012-07-27T18:02:32.633 回答
-1
<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>
于 2012-07-27T18:06:49.153 回答