Skip to content

Instantly share code, notes, and snippets.

@callmehiphop
Created May 15, 2014 19:54
Show Gist options
  • Save callmehiphop/9cb1f50f4a60bc38ca65 to your computer and use it in GitHub Desktop.
Save callmehiphop/9cb1f50f4a60bc38ca65 to your computer and use it in GitHub Desktop.
Heartbeat!
var lastConnectionState;
var speed = 10000;
var endpoint = 'http://www.reddit.com/.json';
(function checkConnection () {
var xhr = new XMLHttpRequest();
var connectionState;
// probably better if we do not make this call async for a couple of reasons
// 1. we're in a separate thread, so this will not block the UI
// 2. if a request takes longer than the timeout, weird things might happen
// 3. no callback messiness
try {
xhr.open('GET', endpoint, false);
xhr.send();
} catch (e) {
// shush you!
}
connectionState = xhr.status >= 200 && xhr.status < 300 || xhr.status === 304;
// did we have a state change?
if (lastConnectionState !== connectionState) {
lastConnectionState = connectionState;
// let the browser know our connection state changed..
postMessage(connectionState);
}
// start the process all over again!
setTimeout(checkConnection, speed);
}());
<!doctype html>
<html>
<head>
<title>Heartbeat Test</title>
</head>
<body>
<div>State: <span id="state"></span></div>
<script>
var $state = document.getElementById('state');
var heartbeat = new Worker('heartbeat.js');
heartbeat.onmessage = function (e) {
var state = e.data ? 'Connected' : 'Not Connected';
$state.innerHTML = state;
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment