0

I'm trying to make a countdown timer with JavaScript but there are two things that I cannot change which are the two digits that supposed to show like this "01:00", but instead it appears like this "1:9", and a phrase that show besides the timer which is "This is only valid for the next ". I'm trying to remove it and I've failed.

<html>
  <head>
 <title>Countdown</title>
 <script type="text/javascript">
 // set minutes
var mins = 20;

// calculate the seconds (don't change this! unless time progresses at a           different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
 function Decrement() {
if (document.getElementById) {
    minutes = document.getElementById("minutes");
    seconds = document.getElementById("seconds");
    // if less than a minute remaining
    if (seconds < 59) {
        seconds.value = secs;
    } else {
        minutes.value = getminutes();
        seconds.value = getseconds();
    }
    secs--;
    setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
</head>
<body>

<div id="timer">
This is only valid for the next <input id="minutes" type="text"    style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;"> : <input id="seconds" type="text" style="width: 60px; border:    none; background-color:none; font-size: 50px; font-weight: bold;"> 
</div>
<script>
   countdown();
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user76449
  • 55
  • 1
  • 9

2 Answers2

0

try this

function getminutes() {
    // minutes is seconds divided by 60, rounded down
    mins = Math.floor(secs / 60);
    return ("0" + mins).substr(-2);
}
function getseconds() {
    // take mins remaining (as seconds) away from total seconds remaining
    return ("0" + (secs-Math.round(mins *60))).substr(-2);
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

To pad a zero simply do:

var renderedSecs;

renderedSecs = (secs < 10 ? "0" : "") + secs;

// now put renderedSecs into the HTML

Don't do this with secs because it is a number, while renderedSecs is a string.

Keep the actual numbers for your computation apart from their rendering (as strings).

pid
  • 11,472
  • 6
  • 34
  • 63