【问题标题】:Start interval when the next minute starts下一分钟开始时的开始间隔
【发布时间】:2019-08-10 10:21:27
【问题描述】:

在我正在开发的日程/日历应用程序中,我会显示一条线来指示当前时间。我想每分钟更新一次这条线的位置。

如果我在日历组件已挂载或将要挂载时启动 setInterval 函数,则会发生变化,它从第 59 秒(或不是第 1 秒)开始,并且时间将始终不同于设备正在显示(计算机、智能手机等)。

但我希望这两个时间都匹配。所以我想知道是否可以在新的一分钟开始时开始间隔,是否有另一种方法来获取时间更新。

编辑:当前代码

componentDidMount() {
    setInterval(() => {
        this.setState({ currentTime: new Date() })
    }, 60 * 1000);
}

【问题讨论】:

  • 只需在循环中使用新日期

标签: javascript reactjs time setinterval


【解决方案1】:

使用 SetTimeout 调用一个函数,该函数修复每次迭代的任何偏差,并通过对 setTimout 的新调用重新启动。

function repairAndRelaunch (cnt) {
    // capture current secs
    var secs = (new Date()).getSeconds();
    // relaunch with corrected seconds - limit iterations for testing
    if (5 > cnt++) setTimeout('repairAndRelaunch(' + cnt + ')', (60-secs)*1000); 
    // log to observe discrepencies
    console.log('for cnt = ' + cnt + ', secs = ' + secs);
};

// test control flow
window.onload = function() {repairAndRelaunch(0);};

【讨论】:

    【解决方案2】:

    您可以通过计算距离下一分钟的秒数并在差值上执行超时来相当接近。

    (function showTime(){
      console.log('update time');
      var time = document.getElementById('time');
      var now = new Date();
      
      time.innerHTML = `${now.getHours()}:${now.getMinutes()}`;
      setTimeout(showTime, (60 - now.getSeconds()) * 1000);
    })();
    <div id="time"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-26
      • 2020-02-28
      • 1970-01-01
      • 2014-01-26
      • 2019-01-16
      • 2019-03-03
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多