Daniel Oliveira
Daniel Oliveira

Reputation: 1290

Nodejs/Javascript dynamic interval

I am creating a HTML5 game with NodeJS (using websockets). To update my the game and send the data to every player I use setInterval() with a 33ms interval (to update 30 times per second).

It happens that when over 10 players connect to the game, the websockets library starts to consume a lot of CPU and the setInterval start to having some delay (it goes to 27-28 frames per second).

After profiling my code I found out that most of the time my CPU is idle. So I was thiking. Is my whole program idle in that 33ms interval beetwen every loop? Would it work if I set a dynamic interval? Something like when a lot of players are connected and the frames per second starts to drop I reset the interval from 33ms to 28ms for example? Could this work/have anyone use any system like this?

Best regards, Daniel

Upvotes: 1

Views: 546

Answers (1)

Jacob Wilson
Jacob Wilson

Reputation: 430

I understand you problem a lot more clearly now. I'm not sure how I'd tackle that. I found a similar question and the solution was not to use setInterval but rather setTimeout. I think the same logic could be applied once you calculate the time it took for the loop to execute.

javascript while loop or set interval with dynamic delay

EDIT

Would also like to include this thanks to @Bergi How to create an accurate timer in javascript?

Upvotes: 1

Related Questions