Skip to content

Instantly share code, notes, and snippets.

Last active February 23, 2022 17:09
Show Gist options
  • Save sahat/8364120 to your computer and use it in GitHub Desktop.
Save sahat/8364120 to your computer and use it in GitHub Desktop.
Calculate client-server latency using
var socket = io.connect('http://localhost');
var startTime;
setInterval(function() {
startTime =;
}, 2000);
socket.on('pong', function() {
latency = - startTime;
io.sockets.on('connection', function (socket) {
socket.on('ping', function() {
Copy link

@flower1024 @steel-finger sounds like you two don't know what a callback is. very dangerous !

Copy link

Can be kind enough to put an example here that isn't "very dangerous"?

Copy link

danneu commented Dec 13, 2015

@jpattisoninc Foxhunt's example isn't dangerous.

// Client

socket.emit('latency',, function(startTime) {
    var latency = - startTime;

// Server

socket.on('latency', function (startTime, cb) {

While it looks magical that the server can "call" cb(), calling cb() on the server really just sends a message back to the client telling it to execute its callback with some given arguments.

It's more clear if you try console.log(cb.toString()) on the server.

Copy link

tcaer commented May 10, 2017

Is this is milliseconds? Thanks!

Copy link

ping and pong events are already used by for heartbeats so it is not advisable to create custom ping/pong events (name them something different). will send ping/pong messages (heartbeats) automatically and you can control the frequency with the connection options object (I believe default is 20 sec).

Copy link

Hi @ForgeableSum, so how can we use builtin ping/pong to calculate latency ? i didn't found any documentation about that.

Copy link

NeXTs commented Sep 25, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment