I'm making a multiplayer game with a Node.js server, and I'm searching for how to write the game loop.

I'm currently using a setinterval every 15ms, but someone told me that if the code inside the setinterval hasn't finished running after 15ms, it will add delay, and lags.

I have searched and found things like setimmediate, process.nextTick, but I don't know what should I use.

So what is the best way to loop, with he best performance?

  • 1
    \$\begingroup\$ It's very rare in game development for there to be one universal "best" way to do anything. Every solution has trade-offs that make it better in some circumstances, worse in others. I'd recommend implementing your game loop based on the method you've found so far in your searches that makes the most sense to you, or that you find most convenient to use. Other things being equal / unknown, the ability to reason about & maintain your code is worth prioritizing. Then profile how your game runs - does it meet your needs? If so, you're done! If not, ask about solving the specific problem you found. \$\endgroup\$
    – DMGregory
    Apr 29, 2022 at 18:24
  • \$\begingroup\$ well there's no way to make it not add delay if you want something that takes longer than 15ms to run every 15ms. It's not possible for that to not create delay. \$\endgroup\$
    – user253751
    May 3, 2022 at 10:03
  • \$\begingroup\$ Even if the interval runs with perfect timing, the network requests to clients won't be perfectly-timed, so the "it depends on your needs/game" response makes sense. There doesn't seem to be enough context here to properly answer how to go about resolving/navigating the inevitable tradeoffs. \$\endgroup\$
    – ggorlen
    Nov 29, 2022 at 18:25


You must log in to answer this question.

Browse other questions tagged .