问题
I have a background script that uses the setInterval command to do a network request on a routine basis.
I was wondering if the background script can detect if the os goes on sleep or standby so that I can adjust the timer displayed upon resuming the background script. I understand that the setInterval timer is suspended during sleep based on this Answer: What happens to setTimeout when the computer goes to sleep?
Code sample is background.js
set_start_time();
search_set_int = setInterval(function() {
foo();
// Set the Auto Search Start time for the next run
set_start_time();
}, frequency); // Set interval function
var total_time_left_sec = (frequency/1000) - (current_time_unix - start_time_unix)
Thanks
回答1:
Keep a local variable with the timestamp of the last interval run. On normal (no sleep) execution, the timestamp will be about now-period, but on sleep it will be older so you know you come from a sleep. Also do not rely on the interval as your 'tick' for calculating elapsed time Instead remember the starting timestamp and substract from now()
来源:https://stackoverflow.com/questions/23933868/chrome-extension-check-if-background-script-is-running