简体   繁体   中英

Delete messages in socket.io?

I'm working on a socket.io chat applications which appends the message to a div (#message-container) so it's displayed on the page. As messages continue to be sent, it keeps stacking on more messages until the page eventually overflows. What if I want it to show, let's say, the most recent 10 messages instead of the entire conversation history, so after ten messages it'll start deleting the top message to make room for the most recent message?

I have a div in the HTML with an id of message-container,

const messageContainer = document.getElementById('message-container') 

In server.js:

  socket.on('send-chat-message', message => {
    socket.broadcast.emit('chat-message', { message: message, name: users[socket.id] })
    
  })

In script.js:

socket.on('chat-message', data => {
  appendMessage(`${data.name}: ${data.message}`)
})

So that's a simple overview of how it displays messages. What do I do to check the message count and delete them so there's only a certain amount on screen?

Well,your are depending of an HTML element 'message-container' which are not much suitable, instead you could use an array to storage in the current session your function appendMessage() could make a push and then you can manage the messages in a JSON array as you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM