JavaScript ‘wake’ event

For 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;

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

Post.refresh = function(){
  var request = $.get('/posts');

    setTimeout(this.refresh, 4000);

    // ...

Now read this

How to travel around the world for a year

While my last post covered my previous year traveling, writing and programming, this article will go into the specifics of planning your own round the world trip, including flights, costs, activities and accommodation. I’ll show you how... Continue →