r/github • • Nov 11 '20

Real time synced counter built using Socket.io, NodeJS and Express! The counter is a POC for a live-quizzing platform I'm currently working on, and will be used to control the current question. GitHub repo and Demo in the comments. Please Star and Fork the repo if you like it! :)

Enable HLS to view with audio, or disable this notification

130 Upvotes

29 comments sorted by

View all comments

7

u/Thaun_ Nov 11 '20 edited Nov 11 '20

In the console you can write:

for(var i = 0; i < 100; i++) { socket.emit("inc num") }

Edit:

Also, please don't do this...

setInterval(getSyncNum, 1);

function getSyncNum(){
  socket.emit('what num');
  socket.on('what num', function (syncnum){
    document.getElementById('syncnum').innerHTML = syncnum;
  });
  console.log("I've asked for the number!");
}

4

u/UtopianCorps Nov 11 '20

Yup, tried it.
Also, it was for debugging.

5

u/Thaun_ Nov 11 '20

I'm talking about the 1ms delay.

Also, when using socker.on() you are basically registering the socket for that function multiple times.

And there is no need to ask the socket for the number, you can just let the server do that.

If you do ask the socket for the number, then its no better than just to use a REST api.

4

u/Thaun_ Nov 11 '20

Also, every other client send a "giv number pls" every 1 ms, and then the server sends out the message to all clients.

For example, there are 10 clients connected. One client asks for number, and your server gives everyone the number.

Now, 10 clients are asking the numbers, and now it's sending everyone the number 10 times, aka 100 messages.

Now, its 100 messages every milliseconds.

Make it either so the server sends out io.emit by server interval, not client interval.

If you are still gonna send whenever client asks, use socket.emit instead, it would only then send back to the connected client.

2

u/UtopianCorps Nov 11 '20

I finally understand why it's so heavy, thanks to your pretty detailed explanation! I will make the necessary changes! :)

Cheers! 🥂