3

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

Community
  • 1
  • 1
user2738707
  • 125
  • 10
  • Perhaps good solution for your case is to decrease interval to small amount (like 1000 ms) and to send frequent updates to background page with remained time. E.g. `// do job every 60 seconds var remainedTime = 60; setInterval(function() { if (--remainedTime <= 0) { foo(); remainedTime = 60; } chrome.extension.sendMessage({remainedTime: remainedTime}); }, 1000);` – Andrey May 31 '14 at 10:14
  • Thanks for the comment. I'm using this solution since its simple, I think Zig Mandel's point about using setInterval tick for calculating exact elapsed time is a concern although I have not seen it happen. – user2738707 Jun 03 '14 at 06:16

1 Answers1

2

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()

Zig Mandel
  • 19,571
  • 5
  • 26
  • 36
  • Thanks for the idea. The timer is updating every second as it is just a clock. 1. I would need to store the last timestamp run every second 2. Retreive the last time stamp and on resumption calculate the delay between Now and last time stamp and adjust the Timer according to the "delay" – user2738707 Jun 03 '14 at 05:59
  • Yes. For more sophistication, when you detect the sleep, adjust your interval so it happena at the right moment as the period has shifted – Zig Mandel Jun 03 '14 at 12:44