-
-
Save glenjamin/1471640 to your computer and use it in GitHub Desktop.
Asynchronous recursive self executing ping function
This file contains hidden or 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(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; | |
})(); |
This file contains hidden or 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