如何计算当前分钟中剩余的秒数

how to calcuate seconds left in the current minute of the time

本文关键字:分钟 何计算 计算      更新时间:2024-05-04

当时间从12:01变为12:02时,我想更新UI中的时钟。

我可以每60秒做一次setInterval,但可能不会在新分钟的第一秒开始。我如何确保它从第一秒开始?

我想我需要找出当前分钟还剩多少秒,然后执行setTimeout,在秒过去时触发setInterval。

var secondsLeft = ?; //calculate seconds left in this minute
setTimeout(function(){
    setInterval(function(){
        //update clock
    }, 1000 * 60);
}, secondsLeft);

如果moment.js让它更容易,那对我来说没问题。

试试这个:secondsLeft = 60 - new Date().getSeconds()

我会存储旧值,使用requestAnimationFrame查看浏览器是否准备好渲染,并在渲染时检查分钟是否与上次渲染相比发生了变化。