jQuery show setTimeout timer

时间:2012-07-27 17:59:37

标签: javascript jquery timer settimeout

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

谢谢!

2 个答案:

答案 0 :(得分:18)

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);
}

答案 1 :(得分:-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>