jQuery show setTimeout timer

后端 未结 2 1956
遇见更好的自我
遇见更好的自我 2021-02-09 06:06

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!

相关标签:
2条回答
  • 2021-02-09 06:22
    <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>
    
    0 讨论(0)
  • 2021-02-09 06:29

    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);
    }
    
    0 讨论(0)
提交回复
热议问题