Ad

Difference Between Socket.on() And Socket.once()

- 1 answer

On the client side, I used socket.on() and got multiple listeners. I found in one answer to change it to socket.once(), which worked fine. But I couldn't find why. Can someone tell me the diference? and which one is better? Thanks.

Ad

Answer

Socket.on is for register a new handler for the given event.

socket.on('news', (data) => {
  console.log(data);
});
// with several arguments
socket.on('news', (arg1, arg2, arg3) => {
  // ...
});
// or with acknowledgement
socket.on('news', (data, callback) => {
  callback(0);
});

Socket.once is for event listeners only - when you only want to be notified of the next time an event occurs, not for the subsequent times it occurs.

So, socket.once fires the next time the event occurs

socket.on fires every time event occurs

Ad
source: stackoverflow.com
Ad