且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当计算机从睡眠模式重新启动时如何重新启动网络工作者?

更新时间:2023-01-30 10:19:32

似乎没有任何 DOM 事件让我们知道该事件.

There doesn't seem to be any DOM event letting us know about that event.

在我的笔记本上,Chrome 确实会触发一个非标准的 orientationabsolutechange 事件,但我认为并非所有笔记本都具有方向感知硬件,而且同一台机器上的 Firefox 不会触发它.

On my notebook Chrome does fire a non-standard orientationabsolutechange event, but I think not all notebooks have orientation aware hardware and already just Firefox on the same machine doesn't fire it.

但是对于您想要的东西(从 API 提供的时间戳始终保持最新的偏移量),您根本不需要 WebWorker,也不需要任何计时器,计算机配备了一个很好的,不仅它仍然是电脑睡眠后更新,它甚至会比你的时间间隔更精确,可能会受到时间漂移的影响.

But for what you want (an always up to date offset from an API served timestamp), you don't need a WebWorker at all, nor any timer, the computer comes with a good one and not only will it still be up to date after computer sleep, it will even be more precise than your interval which can suffer from time-drift.

您所需要的只是存储您从 API 获得的偏移量以及您收到它的计算机时间.然后您只需要获得现在和接收时间之间的差异,您就可以轻松获得更新的偏移量.

All you need is to store the offset you got from your API and the computer's time you received it. Then you just need to get the difference between now and that time of reception and you can easily get your updated offset.

OP 指出,他们担心他们的用户将他们的计算机时间修改为更早的日期,从而在页面运行时弄乱 Date 的值.这可以被检测到.只需存储最后一个值,并检查与当前值的差异是否为负.

OP noted that they are afraid their users modify their computer's time to an earlier date, thus messing up with Date's values while the page is running. This can be detected. All it takes is to store the last value, and check if the difference with the current one is negative.

( async () => {

  const offset_from_API = await getOffsetFromAPI();
  const time_received = Date.now();
  let last_time = time_received;
  
  
  const getUpToDateOffset = () => {
    const now = Date.now();
    // Anti-Back-Time-Travelling check
    // (it's a good idea to poll this method quite often too update `last_time`)
    if( now - last_time < 0 ) {
      throw new Error( 'cheater detected' );
    }
    last_time = now;
    
    return offset_from_API + (now - time_received);

  };
  
  // to compare we will also use an incrementer
  let incremented = offset_from_API;
  setInterval( () => {
    incremented += 1000;
    console.clear();
    console.log( 'incremented', incremented.toLocaleString( 'en-US' ) );
    console.log( 'difference ', getUpToDateOffset().toLocaleString( 'en-US' ) );
  }, 1000 );
  
} )();

function getOffsetFromAPI() { return 1234567; }