Skip to content

Instantly share code, notes, and snippets.

@glenjamin
Forked from makeusabrew/client.js
Created December 13, 2011 10:45
Show Gist options
  • Save glenjamin/1471640 to your computer and use it in GitHub Desktop.
Save glenjamin/1471640 to your computer and use it in GitHub Desktop.
Asynchronous recursive self executing ping function
/**
* Assume our client object manages all communication with the server and other wonderful stuff
*/
var Client = function(socket) {
var that = {};
that.ping = function(limit, callback) {
var results = [];
return _ping(1, results, limit, callback);
};
function _ping(iteration, results, limit, callback) {
var sent = Date.now();
socket.emit('ping', function(timestamp) {
var latency = (Date.now() - sent) / 2;
results.push({
"latency": latency,
"timestamp": timestamp
});
if (iteration < limit) {
return _ping(iteration + 1, results, limit, callback);
} else {
return callback(results);
}
})
}
return that;
})();
Client.ping(10, function(results) {
// results is an array of 10 objects for us to inspect and average out etc.
console.log(results);
});
Client.ping(1, function(result) {
// result is a single array, useful to get current server timestamp etc
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment