I am building a game server using Nodejs. But I have problems running setTimeout maybe because I don't quite understand the concept of the game loop.
Here is my code:
let tickLengthMS = 1000 / 60;
let previousTick = Date.now();
export function gameLoop() {
const now = Date.now();
if (previousTick + tickLengthMS <= now) {
const delta = (now - previousTick) / 1000;
previousTick = now;
update(delta);
}
if (Date.now() - previousTick < tickLengthMS - 16) {
setTimeout(gameLoop);
} else {
setImmediate(gameLoop);
}
}
So this is the game loop that updates my game. And I need to run another loop to send messages to the clients, in a different frequency / timestep.
export function updateNetwork() {
pack = ...
socket.emit('update', pack);
setTimeout(updateNetwork, 1000 / 20);
}
Then I just run:
gameLoop();
updateNetwork();
But it never gets to run the second setTimeout
function. I wonder if the first gameLoop function is blocking the second setTimeout. But isn't setTimeout a non-blocking method? Is the gameLoop function equal to while(true) {}
in other languages such as java and C++?
Updated the question to make two loops.