0

I currently have a timer that works exactly how i want it except when it counts down it displays 2:0 when it should display 2:00. It also displays 1:00,1:01,1:02 etc as 1:0,1:1,1:2 etc . However 1:59 through 1:11 and 0:11 through 0:59 does display correctly. Basicly it is having and issue display 0-9 seconds correctly. Here is my code and a codepen

js

 $(function () {
  var $startTimer = $('#startTimer');
  var $timerDisplay = $('#timerDisplay');
  var time = 120;

  $timerDisplay.hide();

  $startTimer.click(function () {
    $startTimer.prop('disabled', true);
    $timerDisplay.show();
    var timeRemaining = time;
     var intervalId = setInterval(function () {
     var timeStamp = Math.floor(timeRemaining/60) + ':' +    timeRemaining%60;
       $timerDisplay.text(timeStamp);
         if (timeRemaining === 0) {
         clearInterval(intervalId);
        $timerDisplay.fadeOut();
        alert('Time is up, please submit a vote :)');
        $startTimer.prop('disabled', false);
        } else {
        timeRemaining--;
      }
    }, 1000);
  });
});

html

<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>

here is a codepen http://codepen.io/Chevex/pen/RNomGG

Liz Tabbut
  • 41
  • 5
  • This is a standard "how do I display a number with a fixed number of digits" problem. There are 100s of answers out there (and on SO). – iCollect.it Ltd Jan 26 '15 at 14:30
  • possible duplicate of [JavaScript seconds to time string with format hh:mm:ss](http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss) – mplungjan Jan 26 '15 at 14:33

1 Answers1

0

You need to zero pad the number given by timeRemaining%60

There are a number of ways to zero pad in Javascript.

For this application, as it's specific, I recommend replacing:

var timeStamp = Math.floor(timeRemaining/60) + ':' +    timeRemaining%60;

with

var seconds = timeRemaining%60;
seconds = ("0" + seconds).slice (-2);
var timeStamp = Math.floor(timeRemaining/60) + ':' +  seconds;

This works by zero padding every variable seconds and then taking the last two digits - e.g. 0 becomes 00, but 57 becomes 057, but then the slice takes the last two.

J Richard Snape
  • 20,116
  • 5
  • 51
  • 79