Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify computer has awaken from sleep mode with JS

Tags:

javascript

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?

like image 594
mordecai Avatar asked Oct 19 '25 09:10

mordecai


1 Answers

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.

like image 82
Inigo Avatar answered Oct 21 '25 23:10

Inigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!