Search code examples
javascriptjquerycountdown

Countdown alway with two numbers eg: 02:20:02


Hello i have a problem with this code. I have tried several ways but without a success to get zero before hours etc. Also I checked different topics but without a success.

var timestamp = (Date.now() + 1000 * 2 * 60 * 24 * 1) - Date.now();
timestamp /= 1000;

function component(x, v) {
  return Math.floor(x / v);
}

/* last thing i tried but maybe it will help someone
 Number.prototype.pad = function(size) {
 var s = String(this);
 while (s.length < (size || 2)) {s = "0" + s;}
 return s;
 };
*/

var $div = $('div');

setInterval(function () {
  timestamp--;

  var
    hours = component(timestamp, 60 * 60),
    minutes = component(timestamp, 60) % 60,
    seconds = component(timestamp, 1) % 60;

  $div.html(hours + ":" + minutes + ":" + seconds);
}, 1000);

DEMO : http://jsfiddle.net/5z7ahmze/1/

Thank you for your time.


Solution

  • You can check your variable and add a 0 before if needed :

    var comp = component(timestamp, 60 * 60);
    var hour = comp < 10 ? '0' + comp : comp;