1
\$\begingroup\$

I'm making a multiplayer game using socketio + nodejs. Currently I use setInterval on my server and requestAnimation on my client render. Now I want to create multiple game instances for each room and so I ask how to do so efficiently:

  1. Do I initialize a new setInterval for every game created and call clearInterval when that game ends? or...
  2. Should I create only one instance of setInterval and loop through each active game and update them?
  3. Should I be using setInterval at all?

EDIT: For clarification, my current single setInterval simply does this at about 15hz:

-update each player position based on input

-notify all clients of new positions

input is received as soon as the client sends them, handled by socketio. Sending this many emits is intentional because my server is authoritative and my game is slow (imagine a snakes clone). I intend to allow as many games as there are rooms, which is indefinite (or as many as one server can handle)

\$\endgroup\$
  • \$\begingroup\$ Without any context for what you're doing on setinterval(), we can't really advise on any of your questions. Option 2 would be slightly more efficient than option 1, if it meets your needs, but whether that is even worth it depends upon how many game instances you might have. As for option 3, it depends entirely upon what you're doing on setInterval() which you've disclosed nothing about. \$\endgroup\$ – jfriend00 Jan 23 '18 at 1:53
1
\$\begingroup\$

You should remember that nodejs are single-thread. So if you start few setInterval timers with about 15hz - some of times timers may and will start skipping ticks (as setIntercal can do it when loop execution takes more time than interval, or garbage collector doing something every few seconds).

I strongly recommend to NOT start many intervals/loops in single node process. Localize play room into separeted single process, and start as many rooms as want. You can communicate between room's processes using IPC or websockets, with or w/o master process.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Also setInterval can skip tick if function execute longer than interval. And all timers/rooms can skip tick in this case. \$\endgroup\$ – Vladimir Ishenko Apr 30 '18 at 12:35
  • \$\begingroup\$ Good advice. It's also often better to use setTimeout instead, which you can re-start each time the function finishes so that you can avoid issues like that. \$\endgroup\$ – Paul Jul 11 '18 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.