Anonymous
Anonymous

Reputation: 67

Set time in Moment.js

How can I set moment's time to a specific time, let's say 15:45:30. What I want to accomplish is to keep subtracting 1 second from a winded time until it ends up as 00:00:00

Upvotes: 2

Views: 869

Answers (1)

David784
David784

Reputation: 7464

There are a few considerations here:

First: Moment can't natively handle "durations" with greater than 24 hours. If you won't ever have a countdown greater than 23:59:59, you can just use native moment. Otherwise, you could use a plugin, called moment-duration-format.

Second: Using setInterval may not result in exactly the time you specify. It's a minimum, so if you set it to run every 1000 ms, it might actually sometimes run after 1400 ms. Cumulative errors over thousands of calls could be significant.

So it's much more reliable to have a "baseline" epoch, and then subtract that from the current epoch to get the difference between when you started.

That leads to the following example, which puts these together.

var el = document.getElementById('timer');
var dur = moment.duration('94:22:17'); // set the duration
var start = Date.now(); //get benchmark epoch

setInterval(function() {
  var d2 = dur.clone() // clone the duration, so we don't modify the original
    .subtract(Date.now() - start, 'ms'); // subtract the ms since the benchmark from the clone
  el.innerText = d2.format('HH[h] mm[m] ss[s]'); // display formatted version of cloned duration
}, 100);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.min.js" integrity="sha256-M2KULKSJyw+G0068JiMlM9GX4XpLdUButSzBqntKDZM=" crossorigin="anonymous"></script>

<div id='timer'></div>
Note: this is a very simple example. It doesn't watch to see when the timer reaches zero, and will simply go into negative numbers after it hits zero.

credit: I found this moment plugin through this question/answer.

Upvotes: 2

Related Questions