Basically, process.nextTick() defers execution of the function given as its argument until the next "tick", or loop through of the master event loop in node. If you have CPU-intensive code to run, or need something run repetitively (such is the case with a game server), you can set up an event loop-friendly server loop like this:
Code: Select all
function serverMainLoop() {
//do all processing needed for background activity.
//this includes moving around mobs, resolving monster AI
//changing from day to night, and anything else that needs
//to be done but not in response to a player-initiated event
process.nextTick(serverMainLoop);
}
serverMainLoop();
But by instead deferring the next run of the serverMainLoop() function until the next tick of the server, this means that the serverMainLoop() function will not run again until all other events that are queued-up in the event loop have occurred. This means that websocket communications, file I/O, database communication, etc. all get their chance to run before the server loop starts up again.
However, this is not perfect for all situations. If you have a particularly long server loop with tons of processing, you may be better off with real child processes. Also, this method would probably work best by keeping the majority of the game world state in-memory, and simply set up a JS timer to commit it to the database every few minutes.
Hope this helps for anyone out there wanting to use node for an MMORPG or MUD server but who had a hard time grappling with asynchronous programming and the event loop model of node.