2

Which is the best way to manage the time and real-time events ?

I am implementing a small multiplayer RPG game with Node.js. I have many NPCs and each move every 3 or 4 seconds, so i need to update them.

Solution A: use one setTimeout per NPC. if i have hundreds NPCs, i will create as timers. It's more simpler but is it not less efficient ?

Solution B: use one setTimeout for all NPCs. Each time, we call the next timeout by computing the the most small remaining time before a NPC move. So we must use a more complexe code, but we have only one setTimeout.

Has it betters/others way ?

BAK
  • 972
  • 8
  • 23

1 Answers1

0

As the related question says, setTimeout is cheap. However, it's not free.

You could use a single setTimeout in a similar way as memcached works. It has a single big array. Every second, it checks the first item (or last) of this array, and see if there is something that needs to be done. If there is, it does it. Then, it deletes the item. Rinse and repeat.

This is the basic idea behind the implementation. You might get better performance by thinking about empty buckets or stuff like this, but a simple implementation should be quite performant already.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116