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?
setInterval(which isn't covered by any spec) is quite different from the browser'ssetInterval(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.