倒计时器有2位数

时间:2017-04-06 20:40:36

标签: javascript html

我有这个JavaScript代码倒数,我希望计数器在数字小于10时显示两位数(09,08,...)

  (function test() {
   setTimeout(function() {

     $('#id').text(Number($('#id').text()) - 1);
       test();
    }, 1000);
      })();

    //more flexible and modular version 
    function myTimer(elem, maxtime, indexTime ) {
      var i = 0;
     test();
     function test() {
      setTimeout(function () {
        elem.text(i);
        i++;
        if (i < maxtime) {
            test();
         } else {
             console.log('end');
             return false;
        }
      }, indexTime);
    }
    }

1 个答案:

答案 0 :(得分:0)

If I understand, you need something like this?

var initial = $("#id");

function decrease(){
  setTimeout(function() {
    var dec = initial.text() - 1;
    if(dec<10) dec = "0"+dec;
    initial.text(dec);
    if(dec>0)
      decrease();
  },1000);
}
decrease();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id">15</div>