JavaScript 'wake' event
For monocle.io I wanted to ensure that the list of posts is always kept up to date. This is especially a problem when the computer wakes up from a sleep, as the top posts are often way out of date!
It turns out there is no JavaScript wake
event. There is an online
event, but it doesn't seem to trigger whenever the computer is sent to sleep and re-awoken.
The only sure fire way I could work out to achieve this, was to run a interval and check that the it was invoked at the expected times. Any delay in an interval invocation indicates that the computer has just slept.
var TIMEOUT = 20000;
var lastTime = (new Date()).getTime();
setInterval(function() {
var currentTime = (new Date()).getTime();
if (currentTime > (lastTime + TIMEOUT + 2000)) {
// Wake!
}
lastTime = currentTime;
}, TIMEOUT);
You can find the full jQuery plugin here. It triggers a custom wake
event on document
.
$(document).on('wake', function(){ /* ... */ });
The last piece of advice I have, for both the online
and wake
events is that the network connection may not be available. You'd think you'd be able to access remote endpoints when the online
event is triggered - but unfortunately that's not the case.
You'll need to keep polling the network until the request succeeds. Here's an excerpt from monocle.io
Post.refresh = function(){
var request = $.get('/posts');
request.error(function(){
setTimeout(this.refresh, 4000);
}.bind(this));
request.success(function(){
// ...
});
};