JSFiddle - React, Tailwind, and code Playground

by David Buzatto

HTML

<div id="chat"></div>

JavaScript

// processing messages

// messages to be processed
var messages = [{
    id: 1,
    from: "David",
    text: "Test 1"
}, {
    id: 2,
    from: "David",
    text: "Test 2"
}, {
    id: 3,
    from: "David",
    text: "Test 3"
}, {
    id: 4,
    from: "David",
    text: "Test 4"
}, {
    id: 5,
    from: "David",
    text: "Test 5"
}, {
    id: 6,
    from: "David",
    text: "Test 6"
}];

// how many messages the container acepts?
var maxMessages = 3;

// how many messages the container has?
var messageCounter = 0;

// what is the index of the message that is being currently processed
var currentIndex = 0;

// the messages that was processed (It will work like a queue (FIFO)
var processedMessages = [];

// processes one message for each 3 seconds
setInterval( function(){
    
    // the current message
    var message = messages[currentIndex++];
    
    // is there a message to process?
    if ( message ) {
        
        // yes, there is!
        
        // first, removes the oldest if the max quantity was reached
        if ( messageCounter == maxMessages ) {
            
            // the container now will have minus one message
            messageCounter--;
            
            // what is the oldest one?
            // removes from the queue head
            var oldest = processedMessages.pop();
            
            // removes from the container
            $( "#message_" + oldest.id ).remove();
            
        }
        
        // new message incoming!
        messageCounter++;
        
        // inserts the new message at the queue tail
        processedMessages.unshift( message );
        
        // inserts the message in the container
        $( "#chat" ).append( "<div id='message_" + message.id + "'>From " + 
                             message.from + ": " + message.text + "</div>" );
        
    } else {
        
        // there is no message
        currentIndex--;
        
    }
    
}, 3000 );