Skip to content

Instantly share code, notes, and snippets.

@Restuta
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Restuta/6444e056de464af8a0d1 to your computer and use it in GitHub Desktop.
Save Restuta/6444e056de464af8a0d1 to your computer and use it in GitHub Desktop.
momentjs countdown
//bug: in the following case 1d 00h 00m 25s it would not show "00m" since it only checks previous time component
var x = moment()
.add(1, 'month')
.add(1, 'day')
.add(1, 'hour')
.add(1, 'minute')
.add(10, 'seconds');
function format(duration) {
var formattedDuration = '';
//todo restuta: remove that comment if it's no longer relevant
//all except seconds, since we handle them separately, because they require special formatting
var timeComponents = ['y', 'M', 'd', 'h', 'm', 's'];
var previousTimeComponent = null;
for (timeComponent of timeComponents) {
var shouldShowZeroes = false;
/* checking if previous time compoenent is 0 or now so in case when it's not
e.g. 1h 00m 22s we would still show '00' for minutes
and in case it _is zero we would not show anything
e.g. if ther are not hours and no minutes we would how just 22s and not 00h 00m 22s
*/
if (previousTimeComponent && duration.get(previousTimeComponent)) {
shouldShowZeroes = true;
}
if (!duration.get(timeComponent) && shouldShowZeroes) {
formattedDuration += '00' + timeComponent + ' ';
} else if (duration.get(timeComponent)) {
formattedDuration += duration.get(timeComponent) + timeComponent + ' ';
} else {
//do not print anything
}
var previousTimeComponent = timeComponent;
}
//formattedDuration += ' ' + (duration.seconds() || '00') + 's';
return formattedDuration;
}
function countdownStep(timeLeft, intervalId, invervalInMs, elementToWriteTo) {
timeLeft.subtract(invervalInMs, 'milliseconds');
console.log(timeLeft.humanize());
elementToWriteTo.innerText = (format(timeLeft));
if (timeLeft.asMilliseconds() <= 0) {
clearInterval(intervalId);
}
}
//run first timer
var invervalInMs = 1000;
var timeLeft = moment.duration(x - moment());
var intervalId = setInterval(function() {
var elementToWriteTo = document.querySelector('.docs-section-title');
countdownStep(timeLeft, intervalId, invervalInMs, elementToWriteTo);
}, invervalInMs / 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment