H
H
hollanditkzn2018-03-01 14:39:21
JavaScript
hollanditkzn, 2018-03-01 14:39:21

How to add 0 in timer when less than 10?

It is necessary that when a digit enters less than 10 digit, then the digit would not be 1, but 01 should be. My implementation
https://jsfiddle.net/hollanditkzn/0qvwke7o/56/

window.onload = function(){ 
  function timer(){
    let minute = document.getElementById('minute').innerHTML;
    let second = document.getElementById('second').innerHTML;
    let end = false;
    
    if( second > 0 ) {
    second--;
    if( second < 10){
      '0'+second;
    }
    } else{
      second = 60;
      
      if( minute > 0 ) {
      minute--;
      if(minute < 10){
      	'0'+minute
      }
      } else{
        end = true;
      }
    }

    if(end){
      clearInterval(intervalID);
      alert("Время истекло!");
    }else{document.getElementById('minute').innerHTML = minute;
      document.getElementById('second').innerHTML = second;
    }
  }
  window.intervalID = setInterval(timer, 1000);
}

<div id='timer'>
  <div id='minute'>01</div>:
  <div id='second'>10</div>
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2018-03-01
@hollanditkzn

It's easier to make a separate function:

function pad(x) {
  return x < 10 ? '0' + x : x;
}

and use in your code like this:
document.getElementById('minute').innerHTML = pad(minute);
document.getElementById('second').innerHTML = pad(second);

Or you can use the standard one (but not supported by older browsers, if you need their support, do not forget to add the polyfill from the above article).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question