如何将时刻时间设置为特定时间,例如 15:45:30。我想要完成的是不断从冗长的时间中减去 1 秒,直到最终为 00:00:00
最佳答案
这里有一些注意事项:
第一:Moment 本身无法处理超过 24 小时的“持续时间”。如果倒计时不会超过 23:59:59,则可以使用 native 时刻。否则,您可以使用名为 moment-duration-format 的插件。
第二:使用setInterval
可能不会导致完全您指定的时间。这是最小值,因此如果将其设置为每 1000 毫秒运行一次,实际上有时可能会在 1400 毫秒后运行。数千次调用的累积错误可能会很严重。
因此,拥有一个“基线”纪元,然后从当前纪元中减去它,以获得开始时的差异,会更可靠。
这导致了以下示例,它将这些组合在一起。
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>
信用:我通过 this question/answer 找到了 this moment 插件。
关于javascript - 在 Moment.js 中设置时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814581/