3

I'm looking for some way of identifying the computer has awaken from sleep mode. I came across this article that uses Date timestamps inside a setInterval to identify that.

It works perfectly in Firefox but not in the other browsers (Chrome, Safari, and Edge). After around 6min of inactivenness (and without focus) the timestamp difference gets greater than the timeout then triggering the awake function.

var TIMEOUT = 20000;
var lastTime = (new Date()).getTime();

setInterval(function() {
  var currentTime = (new Date()).getTime();
  if (currentTime > (lastTime + TIMEOUT + 2000)) {
    // Wake!
  }
  lastTime = currentTime;
}, TIMEOUT);

Is there any other way to identify that the computer has awaken from sleep mode?

mordecai
  • 529
  • 5
  • 25
  • Why would this information be relevant? What is your goal? – VLAZ Jul 02 '21 at 20:30
  • 2
    Does this answer your question? [Can any desktop browsers detect when the computer resumes from sleep?](https://stackoverflow.com/questions/4079115/can-any-desktop-browsers-detect-when-the-computer-resumes-from-sleep) – S B RAKESH RATH Jul 02 '21 at 20:32

1 Answers1

2

Browsers are getting increasingly aggressive about managing power consumption, especially from inactive windows or tabs. A quick duckduckgo for "safari settimeout javascript inactive throttle" will give you lots of hits. After a certain amount of time, browsers understandably may disregard your requested timeout interval, add exponential lengthening timeouts, or freeze the javascript entirely. I personally am very glad they do.

I doubt there is a way around this, because any loophole would be exploited, and websites would again be to able consume CPU cycles and thus power even when the user hasn't looked at that window tab for hours or days.

If there is (or will be someday) a way around this, it will probably look something like how iOS apps work, where apps are frozen but can request to have a background task be woken up for very specific events.

Inigo
  • 12,186
  • 5
  • 41
  • 70