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 に答える