簡體   English   中英

當計算機從睡眠模式重新啟動時如何重新啟動網絡工作者?

[英]How to restart web workers when computer restarts from sleep mode?

我有一個簡單的網絡工作者,它使用 setInterval 保持時區的當前時間

setInterval(() => {
        userTimezoneTimestamp = userTimezoneTimestamp + 1000
        postMessage(userTimezoneTimestamp);
    }, 1000);

它工作正常,直到我將我的機器置於睡眠模式。 當我從睡眠模式重新啟動機器時,我從這個工人那里得到的時間更長。 只有當機器從睡眠模式啟動時,我才能重新啟動我的網絡工作者?

似乎沒有任何 DOM 事件讓我們知道該事件。

在我的筆記本上,Chrome 確實會觸發一個非標准的orientationabsolutechange事件,但我認為並非所有筆記本都具有方向感知硬件,並且已經只有同一台機器上的 Firefox 不會觸發它。

但是對於您想要的(從 API 提供的時間戳始終保持最新的偏移量),您根本不需要 WebWorker,也不需要任何計時器,計算機配備了一個很好的,不僅它仍然是最新的計算機睡眠后,它甚至會比您的時間間隔更精確,后者可能會受到時間漂移的影響。

您所需要的只是存儲您從 API 獲得的偏移量以及您收到它的計算機時間。 然后您只需要獲得現在和接收時間之間的差異,您就可以輕松獲得更新的偏移量。

OP 指出,他們擔心他們的用戶將他們的計算機時間修改為更早的日期,從而在頁面運行時弄亂Date的值。 這可以被檢測到 所需要的只是存儲最后一個值,並檢查與當前值的差異是否為負。

 ( 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; }

setInterval(() => {
        /*handle userTimezoneTimestamp stuff every N miliseconds */
    }, N);


setInterval(() => {
        userTimezoneTimestamp = userTimezoneTimestamp + 1000
        postMessage(userTimezoneTimestamp);
    }, 1000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM