r/node•
BithTree

Difficulty with regularly emitting from a socket.io server on an interval

I'm trying to create a socket.io server using nestjs. I want to declare a count and loop incrementally to send count + 1. I want it to loop so that the client just receives the next payload without requesting it. In other words, the client connects, listens to 'tick', then console logs out 0, 1, 2, 3, etc. Each number is pushed by the server to the client.

What is the best way to go about this? I'm thinking of setInterval and async generators because most of my code (game of life simulator) is async. The count is just a simple test to get the looping going for the real code. I'm struggling getting the simple test to work. Any tips or links about using loops with websockets?

Posted Jul 15, 2019, 4:25 PM UTC

22
[deleted]•

[deleted]

1
siric_•

Depending on how "accurate" you need the loop timing to be you can either go with setInterval, setImmediate or process.nextTick. It would typically look something like this:

function gameLoop() {
    updateSomethingGameRelated();
    process.nextTick(gameLoop);

}

process.nextTick(gameLoop);

Also if/when you care about game performance, try to avoid socket.io as it comes with a lot of overhead and it's usually better to use raw ws/uws and build your own comm protocol with it.

1
BithTreeOP•

I didn't know about next tick. That seems helpful, thank you. Getting the generator, promises, and setInterval is tough to get to play well for me.

1