-1

I have this JavaScript code that counts down the number and I would like the counter to display two digits when the number is less than 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);
    }
    }
Hodrobond
  • 1,665
  • 17
  • 18
Mufleh
  • 21
  • 4
  • 2
    duplicate of http://stackoverflow.com/questions/12278272/adding-0-if-clock-have-one-digit – Mark Apr 06 '17 at 20:43
  • Checking if a number is < 10 is pretty simple. Adding a 0 to a single digit string is pretty simple as well. Please explain what exact part is difficult for you. – takendarkk Apr 06 '17 at 20:45
  • 5
    Possible duplicate of [Adding "0" if clock have one digit](http://stackoverflow.com/questions/12278272/adding-0-if-clock-have-one-digit) – Przemek Apr 06 '17 at 20:46

1 Answers1

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>