1

I have two absolutely the same setInterval functions on the client side and on the server side:

let i = 0
setInterval(() => {
  console.log(++i)
}, 1000 / 20)

I start this two intervals almost at the same time (thanks to socket.io). But after a short amount of time, they start to be desynchronized. Client code is executed a little faster than the server and this is very strange to me.

CLIENT | SERVER
0      | 0
1      | 1
...    | ...
124    | 120
...    | ...
305    | 193
...    | ...
502    | 484
...    | ...
      etc

I have tried a lot of times, but the result is the same - client code looks faster.

Both client and server are running on the same machine.

What can be the reason of that?

3
  • 1
    Node's setInterval (which isn't covered by any spec) is quite different from the browser's setInterval (which is covered here). But even if it weren't, those would never stay in sync for long. Node's single JavaScript thread could be tied up doing something else, delaying the interval callback. Same with the browser's single main JavaScript thread. The browser's tab could be inactive, and browsers routinely dial-back timers in inactive tabs. If you want them in sync, you'll need a single timer driving both ends. Commented Nov 29, 2017 at 10:35
  • @T.J.Crowder Thanks for the link to the related question, now it looks clear to me. I was thinking that setTimeout is standardized, but that's not true. Commented Nov 29, 2017 at 10:38
  • 1
    :-) It's a bit of a point of contention in the es-discuss (JavaScript) mailing list that they aren't standardized as part of JS's standard lib. But so far, TC39 (the committee that moves JS forward) prefer to leave it as an environment-specific thing. At least it's standardized on browsers now; they used to have lots of subtly-different implementations (like measuring the interval from the beginning of the callback vs. the end, different handling of when the callback takes so long the next interval would be due, etc.). Commented Nov 29, 2017 at 10:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.