m.mikolajczak
m.mikolajczak

Reputation: 124

Different client and server time when using Node.js locally

I have node server working locally and I connect to this server by my webbrowser. I use websocket to communication between client and server. I want to measure accurate time of sending websocket message to the server and from the server. I use javascript function Date.now(), but the problem is that in my results sometimes message was received by server before it was sent by client. I guess that there is difference between client "clock" and server "clock". But there are on the same machine. I will be gratefull for explanation and links for resources.

Upvotes: 1

Views: 451

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138367

As John Resig outlined in one of his blog articles javascripts time is not accurate. The clock you can access with javascript only "ticks" every few milliseconds. That means that it can be roughly ~7ms off the accurate time. Now if your request takes shorter than this small timespan (which can happen if it stays on localhost) it could look like that it was received before it was sent.

 real time: 1000ms
 js time: 1000ms

 travel time: 5ms

 real time: 1005ms
 js time: 998ms // inaccuracy

 difference: -2ms

We can't do anything to improve this as performance.now() was disabled for security reasons. So the only thing we can do is to introduce network latency :), but then the clocks time is probably more off...

Upvotes: 2

Related Questions