Categories
JavaScript Answers

How to Create a Countdown Timer Using Moment.js?

Spread the love

To create a countdown timer using Moment.js, we can use the setInterval function to display the time remaining as time elapses.

For instance, we can write the following HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<div>

</div>

to add the script tag and div.

Then we write:

const eventTime = 1366549200;
const currentTime = 1366547400;
const diffTime = eventTime - currentTime;
let duration = moment.duration(diffTime * 1000, 'milliseconds');
const interval = 1000;
const countdown = document.querySelector('div')

setInterval(() => {
  duration = moment.duration(duration - interval, 'milliseconds');
  countdown.innerText = duration.hours() + ":" + duration.minutes() + ":" + duration.seconds()
}, interval);

to add the countdown logic.

We have the eventTime and currentTime timestamps in milliseconds.

Then we compute their difference and assigned it to diffTime .

We then call moment.duration to get the duration in milliseconds.

Next, we add:

duration = moment.duration(duration - interval, 'milliseconds');

into the setInterval callback to get the duration remaining.

Then we display the time remaining in the div with:

countdown.innerText = duration.hours() + ":" + duration.minutes() + ":" + duration.seconds()

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *