Created
December 13, 2011 08:52
-
-
Save makeusabrew/1471280 to your computer and use it in GitHub Desktop.
Asynchronous recursive self executing ping function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Assume our client object manages all communication with the server and other wonderful stuff | |
*/ | |
var Client = function() { | |
var that = {}; | |
that.ping = function(limit, cb) { | |
var results = []; | |
(function _doPing(iteration) { | |
var sent = new Date().getTime(); | |
// ping the server - we always expect just a timestamp in return | |
socket.emit('ping', function(timestamp) { | |
// take a best-guess at latency based on half the round trip | |
var latency = (new Date().getTime() - sent) / 2; | |
// let's store both the returned timestamp and latency for completeness | |
results.push({ | |
"latency": latency, | |
"timestamp": timestamp | |
}); | |
// check if we need to go again or if we've got enough results | |
if (iteration < limit) { | |
_doPing(iteration+1); | |
} else { | |
cb(results); | |
} | |
}); | |
// always execute the function on iteration 1. Yeah, non zero indexed, but hey... | |
})(1); | |
} | |
return that; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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