任何桌面浏览器都能检测到计算机何时从睡眠状态恢复?

Zak*_*der 57 javascript sleep

如果计算机的"唤醒"事件传播到浏览器并在JavaScript API中可用,那就太好了.有谁知道这样的事情是否实施了?

and*_*wmu 64

我不知道有什么直接的方法可以做到这一点,但是你可以很好地了解它何时发生的一种方法是设置一个运行的setInterval任务,比如每2秒运行一次,并存储它上次运行的时间.然后检查它上次运行的时间是否超过2秒.

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

setInterval(function() {
  var currentTime = (new Date()).getTime();
  if (currentTime > (lastTime + 2000*2)) {  // ignore small delays
    // Probably just woke up!
  }
  lastTime = currentTime;
}, 2000);
Run Code Online (Sandbox Code Playgroud)

  • 这类似于我将如何进行 - 仅使用比2秒更大的间隔:-)我想5分钟将是一个相当小的值(我的计算机很少在任何少量时间内睡觉).另外,另一种方法是记录发生了多少"滴答"与应该发生的次数(保持平均值).还有一个时间变化的边缘情况(DST - 最好使用UTC - 或用户)可能被边缘化. (6认同)
  • 一个好主意,但请记住,当选项卡在后台时,[`setInterval`和`setTimeout`执行速度会受到影响](http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in -background-tabs),这是设计的. (5认同)

小智 22

上面的方法可能遇到的问题之一是警报框或其他模态类型窗口将暂停JS执行可能导致错误的唤醒指示.解决此问题的一种方法是使用Web worker(在较新的浏览器上支持)....

var myWorker = new Worker("DetectWakeup.js");
myWorker.onmessage = function (ev) {
  if (ev && ev.data === 'wakeup') {
     // wakeup here
  }
}

// DetectWakeup.js (put in a separate file)
var lastTime = (new Date()).getTime();
var checkInterval = 10000;

setInterval(function () {
    var currentTime = (new Date()).getTime();

    if (currentTime > (lastTime + checkInterval * 2)) {  // ignore small delays
        postMessage("wakeup");
    }

    lastTime = currentTime;
}, checkInterval);
Run Code Online (Sandbox Code Playgroud)


小智 5

这有点过时了,但根据 Andrew Mu 的回答,我创建了一个简单的 JQuery 插件来做到这一点:https : //github.com/paulokopny/jquery.wakeup-plugin

用法很简单:

$.wakeUp(function(sleep_time) {
    alert("I have slept for " + sleep_time/1000 + " seconds")
});
Run Code Online (Sandbox Code Playgroud)

希望这会在将来对某人有所帮助。