sophistry
sophistry

Reputation: 117

jQuery show setTimeout timer

I'm trying to build a simple countdown application. Is it possible to show the timer value on setTimeout, or would I have to use a for loop?

Thanks!

Upvotes: 7

Views: 25387

Answers (2)

mgraph
mgraph

Reputation: 15338

with setTimeout :

var n = 100;
setTimeout(countDown,1000);

function countDown(){
   n--;
   if(n > 0){
      setTimeout(countDown,1000);
   }
   console.log(n);
}

or using setInterval :

var n = 100;
var tm = setInterval(countDown,1000);

function countDown(){
   n--;
   if(n == 0){
      clearInterval(tm);
   }
   console.log(n);
}

Upvotes: 22

user1558223
user1558223

Reputation: 197

<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>

Upvotes: -1

Related Questions